最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Compare the elements of two arrays by Id and remove the elements from the one array that are not presented in the o

programmeradmin2浏览0评论

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). How can I do this ?

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). How can I do this ?

Share Improve this question asked Feb 20, 2013 at 15:26 MdbMdb 8,56822 gold badges65 silver badges100 bronze badges 1
  • 1 You are seeking the intersection of 2 javascript object arrays. See here: stackoverflow.com/questions/14723412/… – Marc Commented Feb 20, 2013 at 15:29
Add a comment  | 

3 Answers 3

Reset to default 11
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:

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:

"1","3"

That Set is passed as the thisArg to filter, so that within the filter callback it is available as this.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论