Array vs Set: Handling Unique Values
You'll learn when a Set outperforms an Array for managing collections that must contain only unique values.
The Core Problem with Arrays
Arrays allow duplicate values by design. If you need to ensure uniqueness, you must manually check before adding items or filter duplicates afterward. This requires iterating through the array repeatedly, which becomes slow as your collection grows.
const colors = ['red', 'blue', 'red', 'green', 'blue'];
// Removing duplicates with Array - inefficient
const uniqueColors = colors.filter((color, index) =>
colors.indexOf(color) === index
);
console.log(uniqueColors); // ['red', 'blue', 'green']
// Checking if value exists before adding - slow for large arrays
if (!colors.includes('yellow')) {
colors.push('yellow');
}
Why Set Wins for Uniqueness
A Set automatically prevents duplicates and uses optimized internal data structures. Checking membership with has() is dramatically faster than includes() on large arrays.
const colorSet = new Set(['red', 'blue', 'red', 'green', 'blue']);
console.log(colorSet); // Set(3) { 'red', 'blue', 'green' }
// Adding duplicates does nothing
colorSet.add('red'); // Already exists, no change
colorSet.add('yellow'); // New value, added instantly
// Fast membership check
if (colorSet.has('purple')) {
console.log('Found it');
}
When to Choose Set Over Array
- You need guaranteed uniqueness – Set enforces this automatically
- Frequent membership checks –
has()is much faster thanincludes() - Adding/removing values often – Set operations are optimized
- Order doesn't matter much – Sets maintain insertion order but aren't indexed
Stick with arrays when you need positional access, duplicates are intentional, or you rely heavily on array methods like map() and filter().
Key Takeaway: Use Set when uniqueness and fast lookups matter; use Array when you need indexing, duplicates, or rich transformation methods.