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

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

    I'd just map and remove dups:

    var ages = array.map(function(obj) { return obj.age; });
    ages = ages.filter(function(v,i) { return ages.indexOf(v) == i; });
    
    console.log(ages); //=> [17, 35]
    

    Edit: Aight! Not the most efficient way in terms of performance, but the simplest most readable IMO. If you really care about micro-optimization or you have huge amounts of data then a regular for loop is going to be more "efficient".

提交回复
热议问题