Skip to content
Advertisement

javascript Set with objects

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

JavaScript

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

JavaScript

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

Advertisement

Answer

Use a Map to deduplicate by the key name:

JavaScript

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.

Advertisement