Set Since: ES6(ECMAScript 2015)
A collection that stores only unique values. Duplicate values cannot be added, and insertion order is preserved.
Syntax
// Create a new Set. var set = new Set(); // You can also create one with initial values as an array. var set = new Set(["value1", "value2", "value3"]);
Methods and Properties
| Method / Property | Description |
|---|---|
| add(value) | Adds a value. If the same value already exists, it is ignored and no duplicate is stored. |
| has(value) | Returns true or false depending on whether the specified value exists. |
| delete(value) | Removes the specified value. Returns true if the value was successfully deleted, or false if it did not exist. |
| clear() | Removes all values. |
| size | Returns the number of values stored. |
| forEach(function) | Executes a function for each value. |
Sample Code
// Basic Set operations
var colorSet = new Set();
// Add values.
colorSet.add("red");
colorSet.add("blue");
colorSet.add("green");
colorSet.add("red"); // Already exists, so it will not be added.
console.log(colorSet.size); // Outputs '3'. Duplicates are ignored.
// Check if a value exists.
console.log(colorSet.has("blue")); // Outputs 'true'.
console.log(colorSet.has("yellow")); // Outputs 'false'.
// Iterate over all values in order.
colorSet.forEach(function(value) {
console.log(value);
});
// Remove a value.
colorSet.delete("green");
console.log(colorSet.size); // Outputs '2'.
// Example: removing duplicates from an array
var numbers = [1, 2, 3, 2, 1, 4, 3, 5];
var uniqueNumbers = new Set(numbers);
var result = Array.from(uniqueNumbers); // Convert the Set back to an array.
console.log(result); // Outputs '[1, 2, 3, 4, 5]'.
// Shorter syntax using the spread operator
var unique = [...new Set([1, 2, 3, 2, 1])];
console.log(unique); // Outputs '[1, 2, 3]'.
Set vs. Map
| Feature | Set | Map |
|---|---|---|
| What is stored | Values only. | Key-value pairs. |
| Duplicates | Each value can only be stored once. | Each key can only be stored once, but values can be duplicated. |
| Primary use | Managing unique lists and removing duplicates. | Dictionary-style lookups where values are retrieved by key. |
Overview
Set is a collection that stores only unique values. It is a data structure introduced in ES6. Unlike arrays, it cannot store the same value more than once, making it ideal for removing duplicates from an array or quickly checking whether a value exists.
The most common pattern is removing duplicates from an array. You can create a Set with new Set(array) to eliminate duplicates, then convert it back to an array using Array.from() or the spread syntax to get a clean, unique array.
If you need to manage data as key-value pairs, use Map instead.
Browser Compatibility
37 or earlier ×
12 or earlier ×
7 or earlier ×
Android Browser
43+ ○
37 or earlier ×
Chrome Android
43+ ○
37 or earlier ×
Firefox Android
79+ ○
13 or earlier ×If you find any errors or copyright issues, please contact us.