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

前端 未结 30 3116
执笔经年
执笔经年 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 06:09

    Just found this and I thought it's useful

    _.map(_.indexBy(records, '_id'), function(obj){return obj})
    

    Again using underscore, so if you have an object like this

    var records = [{_id:1,name:'one', _id:2,name:'two', _id:1,name:'one'}]
    

    it will give you the unique objects only.

    What happens here is that indexBy returns a map like this

    { 1:{_id:1,name:'one'}, 2:{_id:2,name:'two'} }
    

    and just because it's a map, all keys are unique.

    Then I'm just mapping this list back to array.

    In case you need only the distinct values

    _.map(_.indexBy(records, '_id'), function(obj,key){return key})
    

    Keep in mind that the key is returned as a string so, if you need integers instead, you should do

    _.map(_.indexBy(records, '_id'), function(obj,key){return parseInt(key)})
    

提交回复
热议问题