JavaScript Reference ยท Collections
The Set object
Reference for the JavaScript Set object: create a collection of unique values, remove duplicates from an array, and understand how values are compared.
A Set holds unique values: adding the same value twice leaves one copy. Values can be of any type, and the set remembers the order in which they were first added.
You create one with new Set(), optionally passing an iterable whose items become the initial members. The most common use is removing duplicates from an array: [...new Set(array)].
const empty = new Set(); const letters = new Set(["a", "b", "a"]); // Set { "a", "b" }
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
new Set() new Set(iterable)
| Name | Description |
|---|---|
iterable |
Optional. Any iterable (array, string, another set, a map's keys(), a generator...). Each item becomes a member. null and undefined give an empty set. |
Return value: a new Set object.
Exceptions: a TypeError if called without new, or if iterable is not iterable.
Usage notes
- Equality is "same value zero". Like
===, except thatNaNequalsNaN. Primitives are compared by value; objects, arrays and functions by identity, so two equal-looking objects are two members. - Order is insertion order. Iteration visits members in the order they were first added. Re-adding an existing value does not move it.
- Fast membership test.
set.has(x)takes roughly constant time, whilearray.includes(x)scans the array. Convert a big array to a set when you test membership many times. - A set is not an array. There are no indexes, no
set[0], and nomap()orfilter(). Spread it or useArray.from(set)to get an array. - Copying is shallow.
new Set(set)makes a new set with the same members (objects are shared). - Does not serialize to JSON.
JSON.stringify(new Set([1]))returns"{}"; useJSON.stringify([...set]). - Set of objects by content. Sets cannot deduplicate objects by their fields. Key a
Mapby a string such as an id, or compare viaJSON.stringifyonly if the data is simple. - Weak variant. A WeakSet holds only objects and does not prevent their garbage collection, but it cannot be iterated and has no
size.
Browser support
Set is supported by every current browser and by Node.js. Methods such as union() and intersection() are newer (see Set operations).