Deduplicate arrays
Remove repeated primitive values from incoming arrays or user-provided lists.
JS Puzzles · Const
A Set is a collection of values without keys where each value appears at most once. It is useful for membership checks and removing duplicates.
A Set stores values without keys and enforces uniqueness: adding a value already present has no effect. It can be initialized from an iterable, queried with has(), and converted back to an array when needed; iteration follows insertion order.
new Set(iterable)| Name | Type | Description |
|---|---|---|
iterable | iterable | An optional iterable whose values are copied into the new Set. |
A Set object containing unique values from the optional iterable.
const values = [1, 2, 2, 3, 1];
const uniqueValues = new Set(values);
console.log([...uniqueValues]); // [1, 2, 3]
console.log(uniqueValues.has(2)); // trueConstructing a Set from an iterable keeps each value only once, so spreading it back into an array removes duplicates.
Remove repeated primitive values from incoming arrays or user-provided lists.
Track whether identifiers, permissions, or tags have already been seen.
Maintain a collection that must not contain repeated entries.
A Set is a collection of values rather than key-value pairs, and each value can occur only once. It is useful when membership and uniqueness matter more than indexed access.
Follow-up: How can an array be deduplicated? Construct a Set from the array and spread or convert that Set back into an array.
The constructor accepts an iterable, commonly an array, and adds its elements to the new Set. Duplicate elements are therefore retained only once.
Follow-up: What happens if no iterable is supplied? The constructor creates an empty Set.
A Set can be traversed with for...of or forEach(), and its values are visited in insertion order. This preserves the order in which distinct values were successfully added.
Follow-up: Which operation checks membership without modifying the collection? Use set.has(value), which returns a boolean.
Setnew Set(iterable)Set.prototype.add()Set.prototype.has()Set.prototype.delete()Set.prototype.clear()Set.prototype.size()for...of