简体   繁体   中英

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?

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM