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

前端 未结 30 3238
执笔经年
执笔经年 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.

提交回复
热议问题