如果value存在于数组2中,则从数组1中删除Item

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

本文关键字:数组 Item 删除 存在 value 于数组 如果      更新时间:2023-09-26

数组1

[ { "id": 1, "name": "Test" }, { "id": 2, "name": "Test2" } ]

数组2

[ { "id": 1, "name": "Test3" }, { "id": 2, "name": "Test4" }, { "id": 3, "name": "Test2" } ]

如果item存在于数组2中,我需要从数组1中删除它,因此Test2将从数组1中删除。我如何循环两个数组,并检查数组2中的名称值的存在,以便从数组1中删除它?

我非常喜欢在这种东西上加下划线…

array1 = _.reject(array1, function(e1) {
    return _.find(array2, function(e2) { return e1.name == e2.name });
});

试试这个:

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

要做到这一点而不做O(n^2)搜索,我们可以在每个数组上循环一次,增加一点额外的内存开销。

var map = new Map();
array2.forEach(function(item) {
    map.set(item.name, true);
});
var result = array1.filter(function(item) {
    return !map.has(item.name);
});

注意:我使用Map只是因为它有额外的功能,比如基于任何值设置键。可以使用一个简单的对象