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

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

    var unique = array
        .map(p => p.age)
        .filter((age, index, arr) => arr.indexOf(age) == index)
        .sort(); // sorting is optional
    
    // or in ES6
    
    var unique = [...new Set(array.map(p => p.age))];
    
    // or with lodash
    
    var unique = _.uniq(_.map(array, 'age'));
    

    ES6 example

    const data = [
      { name: "Joe", age: 17}, 
      { name: "Bob", age: 17}, 
      { name: "Carl", age: 35}
    ];
    
    const arr = data.map(p => p.age); // [17, 17, 35]
    const s = new Set(arr); // {17, 35} a set removes duplications, but it's still a set
    const unique = [...s]; // [17, 35] Use the spread operator to transform a set into an Array
    // or use Array.from to transform a set into an array
    const unique2 = Array.from(s); // [17, 35]
    

提交回复
热议问题