Don P
Don P

Reputation: 63597

Underscore.js get an array of unique objects

I have 2 arrays of objects. There are duplicates between the arrays. I want to merge them into 1 array of all unique objects (so no duplicates).

How can I do this by comparing the "id" of each object?

Underscore.js has a method called _.uniq(). It looks to be correct, but I can't get the syntax for the "iterator" argument correct.

var firstArray = [{ id: 1, name: "foo"}, { id: 2, name: "bar" }];
var secondArray = [{ id: 2, name: "boop" }, { id: 3, name: "baz" }];

firstArray.push(secondArray);
var myUniqueArray = _.uniq(firstArray, false, ???);

myUniqueArray // [{ id: 1, name: "foo"}, { id: 2, name: "bar" }, { id: 3, name: "baz" }];

Upvotes: 2

Views: 2610

Answers (2)

jabclab
jabclab

Reputation: 15042

The following should do it:

var myUniqueArray = _.uniq(firstArray.concat(secondArray), false, function (obj) {
    return obj.id;
});

The iteratee here will produce a value on which uniqueness is checked, in this case the id property value.

Here's a JSFiddle.

Upvotes: 1

dfsq
dfsq

Reputation: 193261

You should be able to achieve this with _.uniq method used with second parameter of the property name to be used to filter items:

var firstArray = [{ id: 1, name: "foo"}, { id: 2, name: "bar" }];
var secondArray = [{ id: 2, name: "boop" }, { id: 3, name: "baz" }];

var result = _.uniq(firstArray.concat(secondArray), 'id');

alert(JSON.stringify(result, null, 4));
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

Upvotes: 2

Related Questions