Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS compare two arrays with objects and remove duplicated by property name ES6 way

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

like image 573
test Avatar asked Jan 25 '26 10:01

test


1 Answers

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);
like image 173
ibrahim mahrir Avatar answered Jan 26 '26 23:01

ibrahim mahrir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!