get only the unique value of an array

后端 未结 5 1815
星月不相逢
星月不相逢 2021-01-14 09:16

I am new to javascript and I tried like using distinct but its not what im looking for

example array:

let arr = [ {key:\"1\",value:\"dog\"},
                 


        
5条回答
  •  广开言路
    2021-01-14 09:54

    If you can use Javascript libraries such as underscore or lodash, I recommend having a look at _.xorBy function in their libraries. From lodash:

    _.xorBy([arrays], [iteratee=_.identity])
    

    Basically, you pass in the array that in here is an object literal and you pass in the attribute that you want to all occurrences of remove duplicates with in the original data array, like this:

    var data = [ {key:"1",value:"dog"}
              , {key:"1",value:"dog"}
              , {key:"2",value:"cat"}
              , {key:"3",value:"bird"}
              , {key:"3",value:"bird"}
              ];
    var non_duplidated_data = _.xorBy(data, 'key'); 
    

    Source - https://lodash.com/docs/4.17.14#xorBy

提交回复
热议问题