JSworkinges2015

The Set Data Structure

Collections, refined.

A Set holds a collection of values like an array β€” except every member is unique. The dedup happens for free, and the lookups are O(1).

The dedup trick

Wrapping any iterable in new Set(...) and spreading it back is the shortest path to a unique array. It preserves insertion order, which Object.keys-based tricks famously do not.

Lookup performance

set.has(x) is O(1) average; array.includes(x) is O(n). If you find yourself calling .includes inside a loop, swap the haystack for a Set and watch the runtime collapse.

Object identity, not deep equality

Sets compare with SameValueZero β€” fine for primitives, but {a:1} and {a:1} are still two different objects. For deep dedup, hash to a string key first.

New native operations (2024+)

Modern engines now ship set.union(other), set.intersection(other), set.difference(other), set.symmetricDifference(other), plus isSubsetOf, isSupersetOf, isDisjointFrom.

WeakSet, when you need it

A WeakSet only stores objects and holds them weakly β€” once nothing else references the object, it gets garbage-collected. Useful for marking objects (visited, dirty) without leaking memory.

More patterns

A WeakSet shines as a private "have I touched this object?" flag β€” no extra property on the object, no leak when it's discarded. And when you want the values that are in exactly one of two sets, a sorted symmetric-difference keeps the output stable.

Try it 5 examples

Basic dedup

JSintro
Press Run to execute

The first line collapses the repeated 2s and 3s to [1, 2, 3, 4]; the second keeps only the distinct letters of "mississippi" in first-seen order β€” m, i, s, p. Insertion order is preserved, which the old Object.keys dedup trick can't promise.