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

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

    The forEach version of @travis-j's answer (helpful on modern browsers and Node JS world):

    var unique = {};
    var distinct = [];
    array.forEach(function (x) {
      if (!unique[x.age]) {
        distinct.push(x.age);
        unique[x.age] = true;
      }
    });
    

    34% faster on Chrome v29.0.1547: http://jsperf.com/filter-versus-dictionary/3

    And a generic solution that takes a mapper function (tad slower than direct map, but that's expected):

    function uniqueBy(arr, fn) {
      var unique = {};
      var distinct = [];
      arr.forEach(function (x) {
        var key = fn(x);
        if (!unique[key]) {
          distinct.push(key);
          unique[key] = true;
        }
      });
      return distinct;
    }
    
    // usage
    uniqueBy(array, function(x){return x.age;}); // outputs [17, 35]
    

提交回复
热议问题