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

时间:2013-02-20 15:26:10

标签: javascript jquery

我有两个这样的对象数组:

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的元素})。我怎样才能做到这一点 ?

3 个答案:

答案 0 :(得分:8)

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

垫片,垫片,垫片。

答案 1 :(得分:7)

您可以使用接受任意数量数组的函数,并仅返回所有数组中存在的项。

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

答案 2 :(得分:2)

利用哈希将获得性能提升:

../

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[el.Id]; }, arr2.reduce(function (obj, el) { return obj[el.Id] = 1, obj; }, {})); console.log(arr1);的调用会返回如下所示的哈希:

reduce

该对象以the thisArg to filter传递,因此在{"1":1,"3":1} 回调中,它可以filter的形式提供。