Deduplicate data
Remove repeated primitive values from an array while preserving first-seen order.
JavaScript · Class
Set stores unique values of any type, including primitives and object references. It preserves successful insertion order and provides methods for adding, removing, testing, and iterating values.
A Set is a collection that keeps each value at most once, including primitives and object references. Construct it with an optional iterable, add values with add(), test membership with has(), and traverse values in the order successful additions occurred.
new Set()
new Set(iterable)| Name | Type | Description |
|---|---|---|
iterable | Iterable | An optional iterable whose elements are added to the new Set; omitted, null, or undefined produces an empty Set. |
A new Set object.
const tags = new Set(["js", "web", "js"]);
tags.add("language");
console.log(tags.size); // 3
console.log(tags.has("web")); // true
console.log([...tags]); // ["js", "web", "language"]Creates a Set from an iterable, removes the duplicate string, adds another value, tests membership, and converts the insertion-ordered values to an array.
Remove repeated primitive values from an array while preserving first-seen order.
Check whether an item has already been encountered during processing.
Track object references that have been visited without duplicating the same reference.
Set stores unique values of any type, including primitives and object references. A value can occur only once, and iteration follows successful insertion order.
Follow-up: How are object values compared? They use object identity, so only the same object reference is recognized as the existing value.
Set equality uses SameValueZero. Consequently, NaN is considered equal to NaN, while object values are compared by reference.
Follow-up: What happens with duplicate objects? Distinct object literals remain distinct entries even when their properties are equal.
The constructor accepts an optional iterable, such as an array, and adds its elements to the new Set. If the argument is omitted, null, or undefined, the Set starts empty.
Follow-up: How can a Set be converted to an array? Spread the Set into an array, which consumes its insertion-order iterator.
Set()Set.prototype.add()Set.prototype.clear()Set.prototype.delete()Set.prototype.entries()Set.prototype.forEach()Set.prototype.has()Set.prototype.values()