JavaScript Set Object
A Set is a collection of unique values: each value can appear only once. It is often used to remove duplicates from an array and to check membership quickly.
Description
A Set stores unique values of any type, in the order they were added. Adding a value that is already in the set does nothing. Checking whether a value is present with has() is fast, even for large sets, which makes sets better than arrays for membership tests.
The quickest way to remove duplicates from an array is [...new Set(array)]. Newer browsers also provide set-algebra methods: union(), intersection(), difference(), symmetricDifference(), isSubsetOf(), isSupersetOf() and isDisjointFrom(). Values are compared with SameValueZero, so objects are only equal if they are the same object.
A set can be created from any iterable, including a string, where it collects the unique characters. To work with its contents using array methods, spread it into an array, [...set].filter(...). Sets are iterated in insertion order with for...of or forEach(). Like maps, they don't convert to JSON directly, so convert them to an array before saving or sending them.
Creating
new Set()
new Set(iterable)Instance properties
| Name | Description |
|---|---|
Set.prototype.size | The size property gives the number of values in a Set. |
Instance methods
| Name | Description |
|---|---|
Set.prototype.add() | The add() method adds a value to a Set, unless it is already there. |
Set.prototype.delete() | The delete() method removes a value from a Set. |
Set.prototype.difference() | The difference() method returns a new Set with the values from the first set that aren't in the second. |
Set.prototype.has() | The has() method checks whether a value is in a Set. |
Set.prototype.intersection() | The intersection() method returns a new Set with only the values that both sets have in common. |
Set.prototype.isSubsetOf() | The isSubsetOf() method checks whether every value in a Set is also in another set. |
Set.prototype.union() | The union() method returns a new Set containing every value that is in either set. |
Example
Browser Support
The following information will show you the current browser support for the Set object. Hover over a browser icon to see the version that first introduced support for this object.
Desktop





Tablets & Mobile





