0
existing ["562fae5a626ca2e032947baa"] new array [ { _id: '562fae5a626ca2e032947baa' }, { _id: '562fae57626ca2e032947ba9' } ] modified [ { _id: '562fae5a626ca2e032947baa' }, { _id: '562fae57626ca2e032947ba9' } ] 

I have an existing array and a new array, i want to compare the existing and the new array and remove the duplicates.

var existing = ["562fae5a626ca2e032947baa"]; var newArr = [ { _id: '562fae5a626ca2e032947baa' }, { _id: '562fae57626ca2e032947ba9' } ]; newArr = newArr.filter(function(val){ return existing.indexOf(val) == -1; }); console.log(newArr); 

When i try to print newArr, i still get the two objects?

modified [ { _id: '562fae5a626ca2e032947baa' }, { _id: '562fae57626ca2e032947ba9' } ] 

I want the modified array to have only.

modified [{ _id: '562fae57626ca2e032947ba9' } ] 

Below is the fiddle. http://jsfiddle.net/ema6upg1/2/

2
  • 1
    You're trying to compare the simple string that's in existing to the objects that are in newArr. Commented Oct 27, 2015 at 17:13
  • Are those ids unique for existing? If so, use an object and save yourself some complexity. Commented Oct 27, 2015 at 17:36

3 Answers 3

1
 newArr.filter(function(val){ return existing.indexOf(val._id) == -1; }) 

is what you need, val is an object, you need to compare its _id

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

Comments

1

Your problem is, that one array contains objects.

var existing = ["562fae5a626ca2e032947baa"]; var newArr = [ { _id: '562fae5a626ca2e032947baa' }, { _id: '562fae57626ca2e032947ba9' } ]; newArr = newArr.filter(function(val){ if(typeof val == "object") { return existing.indexOf(val._id) == -1; } return existing.indexOf(val) == -1; }); console.log(newArr); 

Comments

0

The lookup for an object property is more efficient than iterating an array to find an id. Consider:

var existing = { "562fae5a626ca2e032947baa": true }; var newArr = [ { _id: '562fae5a626ca2e032947baa' }, { _id: '562fae57626ca2e032947ba9' } ]; newArr.filter(function(val) { return existing[val._id] || false; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.