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

前端 未结 30 3112
执笔经年
执笔经年 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: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]
    

提交回复
热议问题