A Set is a collection of values where every value is unique. No duplicates allowed. If you try to add something that's already there, nothing happens.
const visitors = new Set();
visitors.add("Mia");
visitors.add("Omar");
visitors.add("Mia"); // already there: ignored!
visitors.add("Zoe");
console.log(visitors);
console.log(visitors.size);
console.log(visitors.has("Omar"));
console.log(visitors.has("Sam"));
visitors.delete("Omar");
console.log(visitors);
It prints
Set(3) { 'Mia', 'Omar', 'Zoe' }
3
true
false
Set(2) { 'Mia', 'Zoe' }| Method / property | What it does |
|---|---|
set.add(value) | Adds a value (if it's not already there) |
set.has(value) | true if the value is in the set |
set.delete(value) | Removes a value |
set.size | How many values (note: size, not length!) |
You can loop over a set with for...of, and turn it into an array with spread. This gives you the most famous one-liner in JavaScript, for removing duplicates from an array:
const votes = ["burger", "omelet", "burger", "pasta", "omelet", "burger"];
const uniqueDishes = [...new Set(votes)];
console.log(uniqueDishes);
It prints
[ 'burger', 'omelet', 'pasta' ]
Remember the "remove duplicates" homework from Grade 7? Yep. One line.
has is also much faster than array.includes when you have lots of items, which makes sets great for things like "have we already seen this?" checks.