2

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

1
  • your question is misleading, property names on all the array are identical, property names and the value of a property are two different things, what do you want ? Commented Apr 11, 2018 at 0:10

3 Answers 3

8

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

Sign up to request clarification or add additional context in comments.

Comments

2

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)

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.