How to create an array of unique values using Set
Set is a built-in JavaScript object that stores unique values. Duplicates are silently ignored. It is the cleanest way to deduplicate an array.
Creating an array of unique values
If you have an array with duplicates, you can remove them in one line:
const result = [...new Set(array)];
Here is a full example. First, extract all categories from a list (which may repeat), then get the unique ones:
const food = [
{ name: 'egg', category: 'breakfast' },
{ name: 'burger', category: 'lunch' },
{ name: 'steak', category: 'dinner' },
{ name: 'chicken', category: 'lunch' },
{ name: 'eggs', category: 'breakfast' },
{ name: 'spaghetti', category: 'dinner' },
];
// Step 1: get all categories (with duplicates)
const allCategories = food.map(item => item.category);
console.log(allCategories); // ['breakfast', 'lunch', 'dinner', 'lunch', 'breakfast', 'dinner']
// Step 2: wrap in Set to remove duplicates, spread back into an array
const uniqueCategories = [...new Set(allCategories)];
console.log(uniqueCategories); // ['breakfast', 'lunch', 'dinner']
Set methods
A Set has its own methods for managing its contents.
const colours = new Set(['red', 'green', 'blue']);
// Check if a value exists
colours.has('red'); // true
colours.has('purple'); // false
// Add a value (duplicates are ignored)
colours.add('yellow');
colours.add('red'); // already there, no effect
// Remove a value
colours.delete('green');
// How many values
colours.size; // 3
// Remove all values
colours.clear();
colours.size; // 0
Iterating over a Set
You can loop over a Set with for...of:
const tags = new Set(['css', 'html', 'javascript']);
for (const tag of tags) {
console.log(tag);
}
// css
// html
// javascript
Or convert to an array first and use array methods:
const tags = new Set(['css', 'html', 'javascript']);
const upper = [...tags].map(t => t.toUpperCase());
console.log(upper); // ['CSS', 'HTML', 'JAVASCRIPT']
Set vs Array
| Set | Array | |
|---|---|---|
| Duplicates | Not allowed | Allowed |
| Order | Insertion order | Insertion order |
| Access by index | No | Yes (arr[0]) |
| Check for value | set.has(val) (fast) | arr.includes(val) (scans the whole array) |
| Size | set.size | arr.length |
Use a Set when uniqueness is what matters. Use an array when you need positional access or array methods like map() and filter().
Common mistakes
Expecting Set to deduplicate objects. Set compares by reference, not by value. Two objects with the same properties are treated as different.
const a = { name: 'Anna' };
const b = { name: 'Anna' };
const s = new Set([a, b]);
s.size; // 2, because a and b are different objects in memory
Using .size on an array. Arrays use .length, not .size. The .size property only exists on Set (and Map).