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

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

    If like me you prefer a more "functional" without compromising speed, this example uses fast dictionary lookup wrapped inside reduce closure.

    var array = 
    [
        {"name":"Joe", "age":17}, 
        {"name":"Bob", "age":17}, 
        {"name":"Carl", "age": 35}
    ]
    var uniqueAges = array.reduce((p,c,i,a) => {
        if(!p[0][c.age]) {
            p[1].push(p[0][c.age] = c.age);
        }
        if(i

    According to this test my solution is twice as fast as the proposed answer

提交回复
热议问题