Set
A collection of unique values. Duplicates are automatically ignored. Lookups are fast and insertion order is preserved.
When to use it
- Deduplication — removing duplicates from an array
- Fast lookups — checking existence without scanning an array
- Tracking seen values — visited IDs, processed items
- Set operations — union, intersection, difference between collections
Anatomy
const s = new Set([1, 2, 3, 2]) // duplicates removed on creation
s.size // 3 — number of unique values
s.has(2) // true — O(1) lookup
s.add(4) // Set {1, 2, 3, 4} — add a value
s.delete(1) // true — remove a value, returns whether it existed
s.clear() // empties the set
// iteration (insertion order preserved)
s.forEach(val => console.log(val))
for (const val of s) { /* ... */ }
// convert back to array
[...s] // [1, 2, 3, 4]
Array.from(s) // [1, 2, 3, 4]
// set operations (ES2025)
s.union(other) // all values from both sets
s.intersection(other) // values in both sets
s.difference(other) // values in s but not in other
s.symmetricDifference(other) // values in either but not both
s.isSubsetOf(other) // true if all s values are in other
s.isSupersetOf(other) // true if s contains all of otherAt a glance
| Method / Property | What it does |
|---|---|
.size | Number of unique values |
.has(value) | Check existence (O(1)) |
.add(value) | Insert a value |
.delete(value) | Remove a value |
.clear() | Remove all values |
.forEach() / for...of | Iterate in insertion order |
[...set] | Convert to array |
.union() | Combine two sets (ES2025) |
.intersection() | Values in both sets (ES2025) |
.difference() | Values in first but not second (ES2025) |
1. Simple — deduplicate an array
const nums = [1, 2, 2, 3, 3, 3]
const unique = [...new Set(nums)]
unique // [1, 2, 3]2. Intermediate — track seen values
function firstDuplicate(arr) {
const seen = new Set()
for (const item of arr) {
if (seen.has(item)) return item // O(1) lookup — fast
seen.add(item)
}
return null // no duplicates
}
firstDuplicate([3, 5, 1, 5, 2]) // 53. Advanced — set operations
const frontend = new Set(['Alice', 'Bob', 'Carol'])
const backend = new Set(['Bob', 'Dave', 'Carol'])
// who works on both?
const fullstack = frontend.intersection(backend)
// Set {'Bob', 'Carol'}
// who is frontend-only?
const frontendOnly = frontend.difference(backend)
// Set {'Alice'}
// everyone across both teams
const everyone = frontend.union(backend)
// Set {'Alice', 'Bob', 'Carol', 'Dave'}Before ES2025, these required manual loops or spreading into arrays with .filter().
Gotchas
Objects are compared by reference
const s = new Set()
s.add({ id: 1 })
s.add({ id: 1 })
s.size // 2 — same shape, different references
// if you need unique-by-value, use a Map keyed by the unique fieldNo index access
const s = new Set(['a', 'b', 'c'])
s[0] // undefined — sets don't support index access
// convert to array first
[...s][0] // 'a'Related
Last updated on