When dealing with arrays in JavaScript, one of the most common problems is duplicate values. Whether you’re cleaning up form inputs, filtering search results, or writing algorithms, you often need to handle uniqueness.
That’s where JavaScript’s built-in Set
comes in — a simple but powerful tool you might not be using enough.
Set
?A Set
is a collection of values where each value must be unique. It’s similar to an array, but with no duplicates allowed.
O(1)
average)const fruits = new Set();fruits.add("apple");fruits.add("banana");fruits.add("apple"); // duplicate — will be ignoredconsole.log(fruits); // Set { 'apple', 'banana' }
You can use a for...of
loop to iterate through the values in a Set
:
for (const fruit of fruits) {console.log(fruit);}// Output:// apple// banana
This is super helpful when you want to process each unique item in a Set.
Method | Description |
---|---|
add(value) | Adds a value |
delete(value) | Removes a value |
has(value) | Checks if a value exists |
clear() | Removes all values |
size | Number of elements in the Set |
const numbers = [1, 2, 2, 3, 4, 4, 5];const uniqueNumbers = [...new Set(numbers)];console.log(uniqueNumbers); // [1, 2, 3, 4, 5]
One-liner to deduplicate an array. Clean. Fast. Beautiful. 😎
Given an array of numbers, return
true
if it contains any duplicates.
function containsDuplicate(nums) {const seen = new Set();for (const num of nums) {if (seen.has(num)) return true;seen.add(num);}return false;}
This is faster and cleaner than sorting or nested loops. The power of Set
!
const mySet = new Set([1, 2, 3]);const myArray = [...mySet]; // [1, 2, 3]
You can go back and forth easily — making Set
a great helper in array operations.
Objects and arrays are compared by reference, not value:
const set = new Set();set.add({ name: "Alice" });set.add({ name: "Alice" });console.log(set.size); // 2 (because they are different objects)
No direct way to get an item by index (like arrays)
Set
Use a Set
when you:
The Set
object is often overlooked but incredibly useful. It can clean up your code, improve performance, and help you ace technical interviews. Next time you think about removing duplicates or checking existence, remember: Set has your back.
📌 Pro tip: Pair Set
with Map
, and you’ll be ready to tackle even more complex data problems in JavaScript!
Quick Links
Legal Stuff
Social Media