How to get unique values in an array

后端 未结 20 2271
情歌与酒
情歌与酒 2020-11-22 14:02

How can I get a list of unique values in an array? Do I always have to use a second array or is there something similar to java\'s hashmap in JavaScript?

I am going

20条回答
  •  爱一瞬间的悲伤
    2020-11-22 14:45

    You only need vanilla JS to find uniques with Array.some and Array.reduce. With ES2015 syntax it's only 62 characters.

    a.reduce((c, v) => b.some(w => w === v) ? c : c.concat(v)), b)
    

    Array.some and Array.reduce are supported in IE9+ and other browsers. Just change the fat arrow functions for regular functions to support in browsers that don't support ES2015 syntax.

    var a = [1,2,3];
    var b = [4,5,6];
    // .reduce can return a subset or superset
    var uniques = a.reduce(function(c, v){
        // .some stops on the first time the function returns true                
        return (b.some(function(w){ return w === v; }) ?  
          // if there's a match, return the array "c"
          c :     
          // if there's no match, then add to the end and return the entire array                                        
          c.concat(v)}),                                  
      // the second param in .reduce is the starting variable. This is will be "c" the first time it runs.
      b);                                                 
    

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

提交回复
热议问题