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

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

    You could use a dictionary approach like this one. Basically you assign the value you want to be distinct as a key in the "dictionary" (here we use an array as an object to avoid dictionary-mode). If the key did not exist then you add that value as distinct.

    Here is a working demo:

    var array = [{"name":"Joe", "age":17}, {"name":"Bob", "age":17}, {"name":"Carl", "age": 35}];
    var unique = [];
    var distinct = [];
    for( let i = 0; i < array.length; i++ ){
      if( !unique[array[i].age]){
        distinct.push(array[i].age);
        unique[array[i].age] = 1;
      }
    }
    var d = document.getElementById("d");
    d.innerHTML = "" + distinct;

    This will be O(n) where n is the number of objects in array and m is the number of unique values. There is no faster way than O(n) because you must inspect each value at least once.

    The previous version of this used an object, and for in. These were minor in nature, and have since been minorly updated above. However, the reason for a seeming advance in performance between the two versions in the original jsperf was due to the data sample size being so small. Thus, the main comparison in the previous version was looking at the difference between the internal map and filter use versus the dictionary mode lookups.

    I have updated the code above, as noted, however, I have also updated the jsperf to look through 1000 objects instead of 3. 3 overlooked many of the performance pitfalls involved (obsolete jsperf).

    Performance

    https://jsperf.com/filter-vs-dictionary-more-data When I ran this dictionary was 96% faster.

提交回复
热议问题