我如何使用下划线获取基于对象属性的唯一数组 [英] How can I get a unique array based on object property using underscore
问题描述
我有一个对象数组,我想从中获得一个仅基于单个属性唯一的新数组,有没有简单的方法来实现这一点?
I have an array of objects and I want to get a new array from it that is unique based only on a single property, is there a simple way to achieve this?
例如.
[ { id: 1, name: 'bob' }, { id: 1, name: 'bill' }, { id: 1, name: 'bill' } ]
将删除2个名称= bill的对象.
Would result in 2 objects with name = bill removed once.
推荐答案
使用 uniq 函数
var destArray = _.uniq(sourceArray, function(x){
return x.name;
});
或单行版本
var destArray = _.uniq(sourceArray, x => x.name);
从文档中
使用===测试对象相等性,产生数组的无重复版本.如果您事先知道数组已排序,则为isSorted传递true将运行更快的算法.如果要基于转换计算唯一项,请传递迭代器函数.
Produces a duplicate-free version of the array, using === to test object equality. If you know in advance that the array is sorted, passing true for isSorted will run a much faster algorithm. If you want to compute unique items based on a transformation, pass an iterator function.
在上面的示例中,该函数使用对象名称来确定唯一性.
In the above example, the function uses the objects name in order to determine uniqueness.
这篇关于我如何使用下划线获取基于对象属性的唯一数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!