How to get unique values in an array

后端 未结 20 1989
情歌与酒
情歌与酒 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:56

    Fast, compact, no nested loops, works with any object not just strings and numbers, takes a predicate, and only 5 lines of code!!

    function findUnique(arr, predicate) {
      var found = {};
      arr.forEach(d => {
        found[predicate(d)] = d;
      });
      return Object.keys(found).map(key => found[key]); 
    }
    

    Example: To find unique items by type:

    var things = [
      { name: 'charm', type: 'quark'},
      { name: 'strange', type: 'quark'},
      { name: 'proton', type: 'boson'},
    ];
    
    var result = findUnique(things, d => d.type);
    //  [
    //    { name: 'charm', type: 'quark'},
    //    { name: 'proton', type: 'boson'}
    //  ] 
    

    If you want it to find the first unique item instead of the last add a found.hasOwnPropery() check in there.

    0 讨论(0)
  • 2020-11-22 14:56

    Here is an approach with customizable equals function which can be used for primitives as well as for custom objects:

    Array.prototype.pushUnique = function(element, equalsPredicate = (l, r) => l == r) {
        let res = !this.find(item => equalsPredicate(item, element))
        if(res){
            this.push(element)
        }
        return res
    }
    

    usage:

    //with custom equals for objects
    myArrayWithObjects.pushUnique(myObject, (left, right) => left.id == right.id)
    
    //with default equals for primitives
    myArrayWithPrimitives.pushUnique(somePrimitive)
    
    0 讨论(0)
提交回复
热议问题