Reputation: 5677
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/
Upvotes: 0
Views: 53
Reputation: 22247
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;
}
Upvotes: 0
Reputation: 312
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);
Upvotes: 1
Reputation: 1497
newArr.filter(function(val){
return existing.indexOf(val._id) == -1;
})
is what you need, val is an object, you need to compare its _id
Upvotes: 1