Michael Michael - 5 months ago 26
Javascript Question

How to remove object from array by property value?

I have this javascript objects:

var arr1 = [{id:'124',name:'qqq'},
{id:'589',name:'www'},
{id:'45',name:'eee'},
{id:'567',name:'rrr'}]

var arr2 = [{id:'124',name:'ttt'},
{id:'45',name:'yyy'}


From arr1 I need remove all objects with the same id in arr2.

Here is the desired result of arr1:

var arr1 = [{id:'589',name:'www'},
{id:'567',name:'rrr'}]


What is elegant way to implement it in Javascript?

Answer

Here is a way to pick up the ID values on the fly. It binds the intermediate object to this via the optional thisArg argument of filter:

var arr1 = [{id:'124',name:'qqq'}, 
           {id:'589',name:'www'}, 
           {id:'45',name:'eee'},
           {id:'567',name:'rrr'}];

var arr2 = [{id:'124',name:'ttt'}, 
           {id:'45',name:'yyy'}];

arr1 = arr1.filter(function (el) {
    return !this[el.id];
}, arr2.reduce(function (obj, el) {
    return obj[el.id] = 1, obj;
}, {}));

console.log(arr1);

The intermediate object that is passed as the last argument to filter looks like this:

{ 45: 1, 124: 1 } 

This makes it straightforward to check if an element of arr1 needs to be rejected or not.