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" }];
1
  • This may help and you do not really need to use an external library. Commented Jul 13, 2015 at 20:40

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.