2

When merging array of strings, I can use Set and ES6 to remove duplicates like so:

const a = ["hello", "hi", "yo"]
const b = ["alo", "hi"]
const remove_hi = [
  ...new Set([
    ...a,
    ...b,
  ]),
]

But how do I compare and remove objects? Say I have this:

const a = [
  {id: "asd", name: "Hi"},
  {id: "fgh", name: "Hello"},
  {id: "123", name: "Hi"}
]
const b = [
  {id: "jkl", name: "Yo"},
  {id: "123", name: "Hi"}
]
// This will not work. It will have a duplicate of {id: "123", name: "Hi"}
const remove_hi = [
  ...new Set([
    ...a,
    ...b,
  ]),
]

How do I remove {id: "123", name: "Hi"} from a combined array with Set?

8
  • I'd stringify the objects first, and store that in the Set Commented Feb 12, 2021 at 22:53
  • Possibly if the position of the objects keys would not change, but there must be a better more elegant way Commented Feb 12, 2021 at 22:55
  • Other ways will require iterating through each item in the Set and checking each object's properties and values. Possible, but extremely cumbersome. If I were in this situation, I'd take a step back and consider if there was a different way to approach the problem other than putting objects into a Set Commented Feb 12, 2021 at 22:56
  • Do you want to deduplicate by id, or by the combination of id and name? Commented Feb 12, 2021 at 22:57
  • 1
    Since you want to deduplicate by name, do you want to keep the fist occurrence or the last occurrence (say the first object had a different id than the second one with the same name, which one should be kept)? Commented Feb 12, 2021 at 23:06

1 Answer 1

3

Use a Map to deduplicate by the key name:

const uniqueBy = (array, key) => [
  ...new Map(
    array.map(o => [key(o), o])
  ).values()
];

const a = [
  {id: "asd", name: "Hi"},
  {id: "fgh", name: "Hello"},
  {id: "123", name: "Hi"}
]
const b = [
  {id: "jkl", name: "Yo"},
  {id: "123", name: "Hi"}
]
const remove_hi = uniqueBy([...a, ...b], o => o.name);

console.log(remove_hi);

Note that deduplicating only by name will remove both {id: "asd", name: "Hi"} and {id: "123", name: "Hi"} since they'd be considered duplicates of the last {id: "123", name: "Hi"} in the array when keying by name.

Replace o.name with whatever key you want to deduplicate by.

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

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.