Sets
In JavaScript, a Set is a built-in collection type that guarantees all of its elements are unique.
Sets are highly optimized for checking whether a specific value exists and are the standard tool for de-duplicating collections of data.
Creating a Set
You instantiate a Set using the new keyword. You can initialize it with an array of elements; the Set will automatically remove any duplicate values.
// Duplicates are automatically discarded
const uniqueNumbers = new Set([1, 2, 3, 4, 5, 5, 5, 5]);
console.log(uniqueNumbers);
// Output: Set { 1, 2, 3, 4, 5 }
Adding and Removing Values
You interact with a Set using its dedicated .add() and .delete() methods.
const players = new Set();
// Adding elements
players.add("Alice");
players.add("Bob");
players.add("Charlie");
// Adding a duplicate does nothing
players.add("Alice");
console.log(players);
// Output: Set { 'Alice', 'Bob', 'Charlie' }
// Removing elements
players.delete("Bob");
console.log(players);
// Output: Set { 'Alice', 'Charlie' }
Practical Example
A very common use case is taking an array that contains duplicates, converting it into a Set to enforce uniqueness, and then converting it back into an array using the spread operator (...).
function deduplicate(itemsArray) {
// 1. Convert the array to a Set (removes duplicates)
const uniqueSet = new Set(itemsArray);
// 2. Spread the Set back into a new Array
return [...uniqueSet];
}
const rawEmails = ["a@a.com", "b@b.com", "a@a.com"];
console.log(deduplicate(rawEmails));
// Output: ["a@a.com", "b@b.com"]