Mdb Mdb - 5 months ago 21
Javascript Question

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

Answer
var new_arr = [];

for (var i=0; i < arr1.length; i++) {
    for (var j=0; j < arr2.length; j++) {
        if ( arr1[i].Id == arr2[j].Id ) {
            new_arr.push( arr1[i] );
        }
    }
}

arr1 = new_arr;

FIDDLE