Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove object from array if it is contained in another array

I am trying to remove an object from an array, if that object's property (unique) is included in the other array. I know I can do a nested for-loop like this:

for(i = 0; i < array.length; i++) {
    for(j = 0; j < array2.length; j++) {
        if(array[i].Email === array2[j].Email) {
            //remove array[i] object from the array
        }
    }
}

Or whatever. Something like that. Is there an ES6 filter for that? I can easily do a filter up against a regular array with strings, but doing it with an array of objects is a bit more tricky.

like image 335
MortenMoulder Avatar asked Dec 14 '22 03:12

MortenMoulder


2 Answers

If you are fine using ES6, you can even look into array.find, array.filter or array.some

Array.findIndex

var result = array.filter(x=>{
  return array2.findindex(t=> t.Email === x.Email) === -1
})

Array.some

var result = array.filter(x=>{
  return !array2.some(t=> t.Email === x.Email)
})
like image 53
Rajesh Avatar answered Feb 15 '23 23:02

Rajesh


Not very optimal, but try this

array = array.filter( function( item ){
  return array2.filter( function( item2 ){
    return item.Email == item2.Email;
  }).length == 0;
});

Try with find as well, it won't iterate all the elements and will break after first match itself

array = array.filter( function( item ){
  return array2.find( function( item2 ){
    return item.Email == item2.Email;
  }) == undefined;
});
like image 21
gurvinder372 Avatar answered Feb 16 '23 01:02

gurvinder372