Hash Set
An unordered collection of unique values with O(1) average-case add, delete, and membership test.
Syntax
const set = new Set([iterable]); Parameters
| Name | Type | Required | Description |
|---|---|---|---|
iterable | Iterable<value> | null | No | An optional iterable of initial values. Duplicate values are silently ignored. |
Returns
Set — A new Set instance containing only unique values.
Examples
// Remove duplicates from an array
const nums = [1, 2, 2, 3, 3, 3, 4];
const unique = [...new Set(nums)];
console.log(unique);
Output
[ 1, 2, 3, 4 ]
// Longest consecutive sequence (O(n) with a Set)
function longestConsecutive(nums) {
const s = new Set(nums);
let best = 0;
for (const n of s) {
if (s.has(n - 1)) continue; // only start from sequence head
let len = 1;
while (s.has(n + len)) len++;
best = Math.max(best, len);
}
return best;
}
console.log(longestConsecutive([100, 4, 200, 1, 3, 2]));
Output
4
Notes
| Operation | Best | Avg | Worst | Space |
|----------|------|------|-------|-------|
| Add | O(1) | O(1) | O(n) | O(n) |
| Has | O(1) | O(1) | O(n) | O(1) |
| Delete | O(1) | O(1) | O(n) | O(1) |
JavaScript's `Set` maintains insertion order and supports
`forEach`, spread, and `for...of`. Unlike a `Map`, it stores only
values (no key-value pairs). Use it for O(1) membership tests
instead of `Array.includes()` which is O(n).