test
test

Reputation: 2466

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

Upvotes: 2

Views: 6743

Answers (3)

aaron.xiao
aaron.xiao

Reputation: 198

a simple and faster sample:

arr1 = [{
  item:"apple",
  description: "lorem"
},{
  item:"peach",
  description: "impsum"
}]

arr2 = [{
  item:"apple", description: "dolor"
},{
  item:"grape", description: "enum"
}]

result = (counters = {}, arr1.concat(arr2).map(cur => (counters[cur.item] ? counters[cur.item]++ : (counters[cur.item] = 1), cur)).filter(cur => counters[cur.item] === 1))

console.log(result)

Upvotes: 0

Arman Charan
Arman Charan

Reputation: 5797

See Set, Array.prototype.filter() and Spread Syntax for more info.

// Join Without Dupes.
const joinWithoutDupes = (A, B) => {
  const a = new Set(A.map(x => x.item))
  const b = new Set(B.map(x => x.item))
  return [...A.filter(x => !b.has(x.item)), ...B.filter(x => !a.has(x.item))]
}

// Proof.
const output = joinWithoutDupes([{item:"apple",description: "lorem"},{item:"peach",description: "impsum"}], [{item:"apple", description: "dolor"},{item:"grape", description: "enum"}])
console.log(output)

Upvotes: 2

ibrahim mahrir
ibrahim mahrir

Reputation: 31712

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

Upvotes: 8

Related Questions