JavaScript array deduplication: get all unique values
P粉779565855
P粉779565855 2023-08-20 11:36:41
0
2
483
<pre class="brush:php;toolbar:false;"><p>I have an array of numbers and I need to make sure the numbers in it are unique. I found the following code snippet on the internet which works fine until there is a zero in the array. I found another almost identical script on Stack Overflow, but it doesn't fail. </p> <p>To help me learn, can anyone help me identify what's wrong with the prototype script? </p> <pre><code>Array.prototype.getUnique = function() { var o = {}, a = [], i, e; for (i = 0; e = this[i]; i ) {o[e] = 1}; for (e in o) {a.push (e)}; return a; }</code></pre> <code> <h3>More answers from duplicate questions: </h3> <ul> <li>Remove duplicate values ​​from JS array</li> </ul> <h3>Similar questions: </h3> <ul> <li>Get all non-unique values ​​in the array (ie: repeated/multiple occurrences)</li> </ul><p><br /></p></code></pre>
P粉779565855
P粉779565855

reply all(2)
P粉153503989

Updated answer for ES6/ES2015: One-line solution using Set and spread operator (thanks le-m) as follows:

let uniqueItems = [...new Set(items)]

The return result is:

[4, 5, 6, 3, 2, 23, 1]
P粉156983446

With JavaScript 1.6 / ECMAScript 5, you can use the array's native filter method to get an array with unique values :

function onlyUnique(value, index, array) {
  return array.indexOf(value) === index;
}

// 使用示例:
var a = ['a', 1, 'a', 2, '1'];
var unique = a.filter(onlyUnique);

console.log(unique); // ['a', 1, 2, '1']
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!