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

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

    Here's another way to solve this:

    var result = {};
    for(var i in array) {
        result[array[i].age] = null;
    }
    result = Object.keys(result);
    

    I have no idea how fast this solution is compared to the others, but I like the cleaner look. ;-)


    EDIT: Okay, the above seems to be the slowest solution of all here.

    I've created a performance test case here: http://jsperf.com/distinct-values-from-array

    Instead of testing for the ages (Integers), I chose to compare the names (Strings).

    Method 1 (TS's solution) is very fast. Interestingly enough, Method 7 outperforms all other solutions, here I just got rid of .indexOf() and used a "manual" implementation of it, avoiding looped function calling:

    var result = [];
    loop1: for (var i = 0; i < array.length; i++) {
        var name = array[i].name;
        for (var i2 = 0; i2 < result.length; i2++) {
            if (result[i2] == name) {
                continue loop1;
            }
        }
        result.push(name);
    }
    

    The difference in performance using Safari & Firefox is amazing, and it seems like Chrome does the best job on optimization.

    I'm not exactly sure why the above snippets is so fast compared to the others, maybe someone wiser than me has an answer. ;-)

提交回复
热议问题