The Set data structure
Learn the Set collection that holds unique values.
What is a Set?
A Set is a collection that holds only unique values. You create one with new Set(). If you add the same value a second time, the Set ignores it; no duplicate is created.
Set stores values in insertion order. You add a value, check membership with has, remove it with delete, and read the count with size.
Removing duplicates with Set
The shortest way to remove duplicates from an array is new Set(array). The Set keeps each value once. To get an array back, use Array.from(set) or [...set].
This works for numbers, strings and object references; but objects are compared by reference, not by value. Two separate {} objects are different to a Set.
Exercise Dedupe with Set
Create an array called tags with duplicate values (for example "js" twice). Use a Set to remove duplicates; convert the result into a new array called uniqueTags. Log uniqueTags.length with console.log.
Show example solution
const tags = ["js", "html", "js", "css"];
const uniqueTags = Array.from(new Set(tags));
console.log(uniqueTags.length);
Test yourself
-
What happens if you add the same value to a Set twice?
- An error is thrown
- The second value overwrites the first
- The second add is ignored; the value stays once
- The size of the Set doubles
Show answer
The second add is ignored; the value stays once — Correct. A Set holds only unique values; the second add is ignored.
-
Remove duplicates with Set
const numbers = [1, 2, 2, 3, 3, 3]; const unique = Array.from(new ____(numbers)); console.log(unique);Show answer
const numbers = [1, 2, 2, 3, 3, 3]; const unique = Array.from(new Set(numbers)); console.log(unique); -
What does the following code print?
const s = new Set(); s.add(1); s.add(1); console.log(s.size);- 1
- 2
- 0
- undefined
Show answer
1 — Correct. The second add(1) is ignored; size stays 1.
-
Match the Set methods
- add(val)
- Adds a new value
- has(val)
- Does the value exist?
- delete(val)
- Removes the value
- size
- How many values?