Wanted to compare two arrays with objects and remove duplicate by its property name, I have these two:
arr1 = [{
item:"apple",
description: "lorem"
},{
item:"peach",
description: "impsum"
}]
arr2 = [{
item:"apple", description: "dolor"
},{
item:"grape", description: "enum"
}]
and I wanted this result:
arr3 = [{
item:"peach", description: "impsum"
},{
item:"grape", description: "enum"
}]
I've tried this es6 approach but not working arr3 = arr1.filter(val => !arr2.includes(val));
Array.includes won't work because in javascript {} !== {}. You'll need another way like Array.every to check that every object in the other array doesn't have the same value of the property item as the current object. Also, you need to do both arr1.filter(...) and arr2.filter(...) and concat the results:
arr3 = [].concat(
arr1.filter(obj1 => arr2.every(obj2 => obj1.item !== obj2.item)),
arr2.filter(obj2 => arr1.every(obj1 => obj2.item !== obj1.item))
);
Example:
let arr1 = [{
item:"apple",
description: "lorem"
},{
item:"peach",
description: "impsum"
}];
let arr2 = [{
item:"apple", description: "dolor"
},{
item:"grape", description: "enum"
}];
let arr3 = [].concat(
arr1.filter(obj1 => arr2.every(obj2 => obj1.item !== obj2.item)),
arr2.filter(obj2 => arr1.every(obj1 => obj2.item !== obj1.item))
);
console.log(arr3);
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