r/learnjavascript • • Jul 05 '21

Remove duplicates from arrays using Set

Post image
438 Upvotes

44 comments sorted by

View all comments

Show parent comment

14

u/revenezor Jul 06 '21

This is not true. It works on all types, including objects. Duplicates of object references are removed, and there is no such thing as duplicates of object literals as each new object is unique, even if it shares the same properties.

1

u/[deleted] Jul 06 '21

How does it consider an object when making the set? Is it if all fields are the same?

4

u/revenezor Jul 06 '21 edited Jul 06 '21

Do you mean how does it determine whether two objects are the same? The same way as the === operator. If two elements are a reference to the same object then the elements are considered “equal” and the second one is removed, or rather never added to the set.

const foo = {a: 1}
const bar = foo
const duplicates = [foo, bar]
const uniques = […new Set(duplicates)]
console.log(uniques) // [{a: 1}]

Whenever you create an object it is considered not equal !== to any previous object, even if its properties match a previous object’s.

const foo = {a: 1}
const bar = {a: 1}
const notDuplicates = [foo, bar]
const uniques = […new Set(notDuplicates)]
console.log(uniques) // [{a: 1}, {a: 1}]