How does a JavaScript `Set` determine whether two values are duplicates?
Quick answer
A JavaScript Set keeps values unique using SameValueZero equality. Re-adding a primitive value already in the set does not create another entry. Objects are compared by identity, not by their properties: adding the same object reference twice gives one entry, but two separately created objects with matching properties give two. [S1]
The question, the details, the next step.
A practical checklist
Decide whether uniqueness should mean the same primitive value, the same object reference, or a matching property such as an ID.
For primitives, check whether the same value is being added more than once.
For objects, check whether you are reusing one reference or creating separate objects.
If matching a property defines a duplicate, compare or collect that property explicitly.
When deduplicating records by a property, decide how to handle records that share that property but differ elsewhere.
A few more useful answers
Will two object literals with identical properties count as one Set entry?
No. Separately created objects have separate identities, so both can be stored even when their properties match. [S1]
What happens if I add the same object variable twice?
The variable refers to the same object both times, so the Set contains one entry for that object. [S1]
Can I use a Set to get unique record IDs?
Yes. Add the ID values to a Set rather than adding the record objects. That gives unique IDs, but does not decide which record to keep.
Sources
References used for this guide.
- [S1] Set — JavaScript | MDN developer.mozilla.org · Checked
