user2994560
user2994560

Reputation: 1309

Javascript Remove Item from array 1 if value exists in array 2

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?

Upvotes: 0

Views: 811

Answers (3)

TbWill4321
TbWill4321

Reputation: 8666

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.

Upvotes: 0

Ori Drori
Ori Drori

Reputation: 191976

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;
    });

Upvotes: 0

danh
danh

Reputation: 62676

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 });
});

Upvotes: 1

Related Questions