简体   繁体   English

通过Id比较两个数组的元素,并从一个数组中删除未在另一个数组中显示的元素

[英]Compare the elements of two arrays by Id and remove the elements from the one array that are not presented in the other

I have two arrays of objects like this: 我有两个这样的对象数组:

var arr1 = [{Id: 1, Name: "Test1"}, {Id: 2, Name: "Test2"}, {Id: 3, Name: "Test3"}, {Id: 4, Name: "Test4"}]

var arr2 = [{Id: 1, Name: "Test1"}, {Id: 3, Name: "Test3"}]

I need to compare the elements of the two arrays by Id and remove the elements from arr1 that are not presented in arr2 ( does not have element with that Id ). 我需要通过Id比较两个数组的元素,并从arr1中删除未在arr2中显示的元素(没有带有该Id元素)。 How can I do this ? 我怎样才能做到这一点 ?

var res = arr1.filter(function(o) {
    return arr2.some(function(o2) {
        return o.Id === o2.Id;
    })
});

shim, shim, shim. 垫片,垫片,垫片。

You can use a function that accepts any number of arrays, and returns only the items that are present in all of them. 您可以使用接受任意数量数组的函数,并仅返回所有数组中存在的项。

function compare() {
    let arr = [...arguments];
    return arr.shift().filter( y => 
        arr.every( x => x.some( j => j.Id === y.Id) )
    )
}

 var arr1 = [{Id: 1, Name: "Test1"}, {Id: 2, Name: "Test2"}, {Id: 3, Name: "Test3"}, {Id: 4, Name: "Test4"}]; var arr2 = [{Id: 1, Name: "Test1"}, {Id: 3, Name: "Test3"}, {Id: 30, Name: "Test3"}]; var arr3 = [{Id: 1, Name: "Test1"}, {Id: 6, Name: "Test3"}, {Id: 30, Name: "Test3"}]; var new_arr = compare(arr1, arr2, arr3); console.log(new_arr); function compare() { let arr = [...arguments] return arr.shift().filter( y => arr.every( x => x.some( j => j.Id === y.Id) ) ) } 

Making use of a hash (a Set) will give a performance gain: 使用散列(Set)将获得性能提升:

 var arr1 = [{Id: 1, Name: "Test1"}, {Id: 2, Name: "Test2"}, {Id: 3, Name: "Test3"}, {Id: 4, Name: "Test4"}]; var arr2 = [{Id: 1, Name: "Test1"}, {Id: 3, Name: "Test3"}]; arr1 = arr1.filter(function (el) { return this.has(el.Id); }, new Set(arr2.map(el => el.Id))); console.log(arr1); 

A new Set is created that gets the Id values from arr2 : 创建一个新的Set ,从arr2获取Id值:

"1","3"

That Set is passed as the thisArg to filter , so that within the filter callback it is available as this . 该Set作为thisArg传递filter ,因此在filter回调中它可以this

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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