How to get distinct values from an array of objects in JavaScript?

前端 未结 30 2525
执笔经年
执笔经年 2020-11-22 05:29

Assuming I have the following:

var array = 
    [
        {\"name\":\"Joe\", \"age\":17}, 
        {\"name\":\"Bob\", \"age\":17}, 
        {\"name\":\"Carl\         


        
相关标签:
30条回答
  • 2020-11-22 06:06

    underscore.js _.uniq(_.pluck(array,"age"))

    0 讨论(0)
  • 2020-11-22 06:07

    Using Lodash

    var array = [
        { "name": "Joe", "age": 17 },
        { "name": "Bob", "age": 17 },
        { "name": "Carl", "age": 35 }
    ];
    
    _.chain(array).map('age').unique().value();
    

    Returns [17,35]

    0 讨论(0)
  • 2020-11-22 06:08
    function get_unique_values_from_array_object(array,property){
        var unique = {};
        var distinct = [];
        for( var i in array ){
           if( typeof(unique[array[i][property]]) == "undefined"){
              distinct.push(array[i]);
           }
           unique[array[i][property]] = 0;
        }
        return distinct;
    }
    
    0 讨论(0)
  • 2020-11-22 06:09

    There are many valid answers already, but I wanted to add one that uses only the reduce() method because it is clean and simple.

    function uniqueBy(arr, prop){
      return arr.reduce((a, d) => {
        if (!a.includes(d[prop])) { a.push(d[prop]); }
        return a;
      }, []);
    }
    

    Use it like this:

    var array = [
      {"name": "Joe", "age": 17}, 
      {"name": "Bob", "age": 17}, 
      {"name": "Carl", "age": 35}
    ];
    
    var ages = uniqueBy(array, "age");
    console.log(ages); // [17, 35]
    
    0 讨论(0)
  • 2020-11-22 06:09

    Just found this and I thought it's useful

    _.map(_.indexBy(records, '_id'), function(obj){return obj})
    

    Again using underscore, so if you have an object like this

    var records = [{_id:1,name:'one', _id:2,name:'two', _id:1,name:'one'}]
    

    it will give you the unique objects only.

    What happens here is that indexBy returns a map like this

    { 1:{_id:1,name:'one'}, 2:{_id:2,name:'two'} }
    

    and just because it's a map, all keys are unique.

    Then I'm just mapping this list back to array.

    In case you need only the distinct values

    _.map(_.indexBy(records, '_id'), function(obj,key){return key})
    

    Keep in mind that the key is returned as a string so, if you need integers instead, you should do

    _.map(_.indexBy(records, '_id'), function(obj,key){return parseInt(key)})
    
    0 讨论(0)
  • 2020-11-22 06:09

    I wrote my own in TypeScript, for a generic case, like that in Kotlin's Array.distinctBy {}...

    function distinctBy<T, U extends string | number>(array: T[], mapFn: (el: T) => U) {
      const uniqueKeys = new Set(array.map(mapFn));
      return array.filter((el) => uniqueKeys.has(mapFn(el)));
    }
    

    Where U is hashable, of course. For Objects, you might need https://www.npmjs.com/package/es6-json-stable-stringify

    0 讨论(0)
提交回复
热议问题