How can I get a unique array based on object prope

2019-02-03 23:42发布

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?

Eg.

[ { id: 1, name: 'bob' }, { id: 1, name: 'bill' }, { id: 1, name: 'bill' } ]

Would result in 2 objects with name = bill removed once.

7条回答
forever°为你锁心
2楼-- · 2019-02-04 00:11

Use the uniq function

var destArray = _.uniq(sourceArray, function(x){
    return x.name;
});

From the docs:

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.

查看更多
登录 后发表回答