2

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" }];
Don P
  • 60,113
  • 114
  • 300
  • 432
  • [This may help](http://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript-and-de-duplicate-items) and you do not really need to use an external library. – ODelibalta Jul 13 '15 at 20:40

2 Answers2

2

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>
dfsq
  • 191,768
  • 25
  • 236
  • 258
1

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.

jabclab
  • 14,786
  • 5
  • 54
  • 51