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

前端 未结 30 2521
执笔经年
执笔经年 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 05:44

    For those who want to return object with all properties unique by key

    const array =
      [
        { "name": "Joe", "age": 17 },
        { "name": "Bob", "age": 17 },
        { "name": "Carl", "age": 35 }
      ]
    
    const key = 'age';
    
    const arrayUniqueByKey = [...new Map(array.map(item =>
      [item[key], item])).values()];
    
    console.log(arrayUniqueByKey);
    
       /*OUTPUT
           [
            { "name": "Bob", "age": 17 },
            { "name": "Carl", "age": 35 }
           ]
       */
    
     // Note: this will pick the last duplicated item in the list.

    0 讨论(0)
  • 2020-11-22 05:44

    Simple distinct filter using Maps :

    let array = 
        [
            {"name":"Joe", "age":17}, 
            {"name":"Bob", "age":17}, 
            {"name":"Carl", "age": 35}
        ];
    
    let data = new Map();
    
    for (let obj of array) {
      data.set(obj.age, obj);
    }
    
    let out = [...data.values()];
    
    console.log(out);

    0 讨论(0)
  • 2020-11-22 05:44
    [...new Set([
        { "name": "Joe", "age": 17 },
        { "name": "Bob", "age": 17 },
        { "name": "Carl", "age": 35 }
      ].map(({ age }) => age))]
    
    0 讨论(0)
  • 2020-11-22 05:45

    You may be interested in unique set of objects based on one of the keys:

    let array = 
    [
        {"name":"Joe", "age":17}, 
        {"name":"Bob", "age":17}, 
        {"name":"Carl", "age": 35}
    ]
    let unq_objs = [...new Map(array.map(o =>[o["age"], o])).values()];
    console.log(unq_objs)
    //result
    [{name: "Bob", age: 17},
    {name: "Carl", age: 35}]
    
    0 讨论(0)
  • 2020-11-22 05:45

    Simple one-liner with great performance. 6% faster than the ES6 solutions in my tests.

    var ages = array.map(function(o){return o.age}).filter(function(v,i,a) {
        return a.indexOf(v)===i
    });
    
    0 讨论(0)
  • 2020-11-22 05:47

    If you are using ES6/ES2015 or later you can do it this way:

    const data = [
      { group: 'A', name: 'SD' }, 
      { group: 'B', name: 'FI' }, 
      { group: 'A', name: 'MM' },
      { group: 'B', name: 'CO'}
    ];
    const unique = [...new Set(data.map(item => item.group))]; // [ 'A', 'B']
    

    Here is an example on how to do it.

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