Array 1
[ { "id": 1, "name": "Test" }, { "id": 2, "name": "Test2" } ]
Array 2
[ { "id": 1, "name": "Test3" }, { "id": 2, "name": "Test4" }, { "id": 3, "name": "Test2" } ]
If item exists in Array 2, I need to remove it from Array 1, so Test2 would be removed from Array 1. How can I loop through both arrays and check the name value's presence in Array 2 in order to remove it from Array 1?
asked Aug 28, 2015 at 23:27
user2994560
1,3195 gold badges18 silver badges30 bronze badges
3 Answers 3
I'm a big fan of underscorejs for this kind of thing...
array1 = _.reject(array1, function(e1) {
return _.find(array2, function(e2) { return e1.name == e2.name });
});
answered Aug 28, 2015 at 23:38
danh
62.8k10 gold badges100 silver badges139 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Try this:
var existingIds = array2.map(function (item) { // create a list of existing ids in array 2
return item.id;
});
var filteredArray = array1.filter(function (item) { // check each item against existingIds, and if not found there return it
return existingIds.indexOf(item.id) === -1;
});
answered Aug 28, 2015 at 23:46
Ori Drori
196k32 gold badges243 silver badges233 bronze badges
Comments
To do this without doing an O(n^2) search, we can do it looping once on each array, with a little extra memory overhead.
var map = new Map();
array2.forEach(function(item) {
map.set(item.name, true);
});
var result = array1.filter(function(item) {
return !map.has(item.name);
});
Note: I used Map simply because it has additional features, such as setting keys based on any value. A simple object can be used.
answered Aug 28, 2015 at 23:47
TbWill4321
8,6863 gold badges30 silver badges25 bronze badges
Comments
lang-js
1not removed?name, notid?array_filterfor this.Array.prototype.filter.