通过Id比较两个数组的元素,并从一个数组中删除未在另一个数组中显示的元素 [英] Compare the elements of two arrays by Id and remove the elements from the one array that are not presented in the other
本文介绍了通过Id比较两个数组的元素,并从一个数组中删除未在另一个数组中显示的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个这样的对象数组:
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"}]
我需要通过 Id
比较两个数组的元素,并从 arr1
中删除不属于的元素在 arr2
中显示(没有 Id
的元素)。我怎样才能做到这一点 ?
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
). How can I do this ?
推荐答案
您可以使用接受任意数量数组的函数,并仅返回所有数组中存在的项。
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) )
)
}
这篇关于通过Id比较两个数组的元素,并从一个数组中删除未在另一个数组中显示的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文