仅获取数组的唯一值 [英] get only the unique value of an array

查看:57
本文介绍了仅获取数组的唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对javascript还是陌生的,我尝试过使用distinct,但不是我想要的

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

示例数组:

let arr = [ {key:"1",value:"dog"},
            {key:"1",value:"dog"},
            {key:"2",value:"cat"},
            {key:"3",value:"bird"},
            {key:"3",value:"bird"},
          ]

在我尝试的代码上,它只是删除了

on the code I try is its just removing the duplicate like

[ {key:"1",value:"dog"},
  {key:"2",value:"cat"},
  {key:"3",value:"bird"}, ]

我怎么只能得到

[ {key:"2",value:"cat"} ]

我的意思是只有一个没有重复项并删除那些完全相同的数组吗?

what I mean is only the one who have no duplicate and its removing those array that have the exact same?

推荐答案

如果可以使用下划线或lodash之类的Javascript库,建议您查看其库中的_.xorBy函数.来自lodash:

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'); 

来源- https://lodash.com/docs/4.17.14#xorBy

这篇关于仅获取数组的唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆