amiawizard amiawizard - 1 month ago 5
Javascript Question

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?

Eg.

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


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

Answer

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.