Search code examples
javascriptecmascript-6

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.


Solution

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