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

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

    My below code will show the unique array of ages as well as new array not having duplicate age

    var data = [
      {"name": "Joe", "age": 17}, 
      {"name": "Bob", "age": 17}, 
      {"name": "Carl", "age": 35}
    ];
    
    var unique = [];
    var tempArr = [];
    data.forEach((value, index) => {
        if (unique.indexOf(value.age) === -1) {
            unique.push(value.age);
        } else {
            tempArr.push(index);    
        }
    });
    tempArr.reverse();
    tempArr.forEach(ele => {
        data.splice(ele, 1);
    });
    console.log('Unique Ages', unique);
    console.log('Unique Array', data);```
    

提交回复
热议问题