Home  >  Q&A  >  body text

JavaScript array deduplication: get all unique values

<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粉779565855P粉779565855427 days ago464

reply all(2)I'll reply

  • P粉153503989

    P粉1535039892023-08-21 10:32:19

    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]

    reply
    0
  • P粉156983446

    P粉1569834462023-08-21 09:27:33

    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']

    reply
    0
  • Cancelreply