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.
If you are fine using ES6, you can even look into array.find
, array.filter
or array.some
var result = array.filter(x=>{
return array2.findindex(t=> t.Email === x.Email) === -1
})
var result = array.filter(x=>{
return !array2.some(t=> t.Email === x.Email)
})
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With