Sets
Overview
A Set (introduced in ES6) is a collection of values where each value must be completely unique.
While Arrays allow duplicate entries (e.g. [1, 1, 1]), Sets silently ignore duplicate insertions. They are incredibly useful for instantly removing duplicates from arrays and performing mathematical set operations.
Syntax
const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(1); // Ignored! 1 already exists.
console.log(mySet.size); // 2
// Check existence (O(1) time complexity - extremely fast!)
console.log(mySet.has(2)); // trueconst duplicateArray = [1, 2, 2, 3, 4, 4, 5];
// 1. Pass the array into a new Set (removes duplicates)
// 2. Use the Spread Operator [...] to unpack the Set back into an Array
const uniqueArray = [...new Set(duplicateArray)];
console.log(uniqueArray); // [1, 2, 3, 4, 5]Common Pitfalls
Adding complex objects to a Set. Because objects are compared by memory reference,
mySet.add({a: 1}); mySet.add({a: 1});will result in TWO items in the Set! Even though they look identical, they occupy different memory addresses, so the Set views them as unique.
Interview Questions
Why is set.has(val) faster than array.includes(val)?
array.includes must loop through the array sequentially from start to finish to find a match (O(n) time). A Set uses hash tables internally, meaning it can instantly verify if a value exists without looping (O(1) time).
Real-World Example
Keeping track of a user's selected tags (e.g., 'React', 'Node') in a multi-select filter. A Set prevents the same tag from being selected twice.
const activeFilters = new Set();
activeFilters.add("React");
activeFilters.delete("Node");Check Your Knowledge
Test your understanding of Sets with these quick questions.