A Set is a collection of unique values. Adding a value that is already there does nothing.
const tags = new Set();
tags.add("js");
tags.add("css");
tags.add("js"); // ignored: already there
console.log(tags.size); // → 2
console.log(tags.has("css")); // → true
tags.delete("css");
console.log([...tags]); // → ["js"]
| Method | Does |
|---|---|
add(value) | adds (returns the set) |
has(value) | is it in there? |
delete(value) | removes it |
clear() | empties it |
size | how many |
Removing duplicates from an array
The most common use.
const numbers = [1, 2, 2, 3, 3, 3];
const unique = [...new Set(numbers)];
console.log(unique); // → [1, 2, 3]
Fast membership checks
set.has(x) is quick, even for large sets. Use a Set when you check “is this in the list?” many times.
const allowed = new Set(["admin", "editor", "author"]);
console.log(allowed.has("editor")); // → true
console.log(allowed.has("guest")); // → false
Looping
const colors = new Set(["red", "green", "blue"]);
for (const color of colors) {
console.log(color);
}
colors.forEach(color => console.log(color));
Sets keep insertion order.
Set operations
const a = new Set([1, 2, 3]);
const b = new Set([2, 3, 4]);
const union = new Set([...a, ...b]);
const intersection = new Set([...a].filter(x => b.has(x)));
const difference = new Set([...a].filter(x => !b.has(x)));
console.log([...union]); // → [1, 2, 3, 4]
console.log([...intersection]); // → [2, 3]
console.log([...difference]); // → [1]
Newer JavaScript has built-in methods for these (union(), intersection()…): Recent Features.
Equality of values
Sets use the same rules as Map keys. Objects are compared by reference, so two different objects with the same content are two entries.
const set = new Set();
set.add({ a: 1 });
set.add({ a: 1 });
console.log(set.size); // → 2
WeakSet (a first look)
A WeakSet holds objects only, and it holds them weakly: if nothing else in the program refers to an object, the garbage collector may remove it, even though it is in the WeakSet. A WeakSet cannot be looped over and has no size, because its contents may disappear at any moment. The methods are add, has and delete.
const visited = new WeakSet();
function markVisited(node) {
visited.add(node);
}
const page = { url: "/home" };
markVisited(page);
console.log(visited.has(page)); // → true
Use it to tag objects without preventing their cleanup, such as “this element has already been processed”. More in WeakMap and WeakSet.