How to Remove Duplicates from an Array in JavaScript
Get the unique values from an array — with a one-line Set for primitives, and a Map when you need to de-duplicate objects by a key.
Overview
For an array of primitives (numbers, strings, booleans), the shortest and fastest way to get the unique values is to build a Set and spread it back into an array. A Set only ever holds distinct values, so duplicates simply fall away — and insertion order is preserved.
const unique = [...new Set(array)];
Steps
1. Primitives — use a Set
const nums = [1, 2, 2, 3, 3, 3];
console.log([...new Set(nums)]); // [1, 2, 3]
const tags = ['a', 'b', 'a', 'c'];
console.log([...new Set(tags)]); // ['a', 'b', 'c']
2. The older filter + indexOf idiom
Before Set, the common trick was to keep an element only at the first index where it appears. It still works for primitives, but it's slower (O(n²)) and has a subtle NaN bug — see the pitfalls below.
const nums = [1, 2, 2, 3];
const unique = nums.filter((value, index, arr) => arr.indexOf(value) === index);
console.log(unique); // [1, 2, 3]
3. Objects — de-duplicate by a key with Map
A Set won't help with objects, because two object literals are never equal (they're compared by reference). Instead, key a Map by the field that defines uniqueness — building it keeps the last occurrence of each key:
const users = [
{ id: 1, name: 'Ada' },
{ id: 2, name: 'Bo' },
{ id: 1, name: 'Ada (updated)' },
];
// Key by id; a later id overwrites an earlier one (keeps the LAST)
const unique = [...new Map(users.map(u => [u.id, u])).values()];
console.log(unique.map(u => u.name)); // ['Ada (updated)', 'Bo']
Runnable example
Edit and run — compare Set with the filter idiom:
Common pitfalls
Need the *first* occurrence of each object instead of the last? Build the Map with a guard: if (!map.has(key)) map.set(key, item) while iterating.
Frequently asked questions
What's the fastest way to remove duplicates from an array?
[...new Set(array)] — it's a single pass and preserves insertion order. It's faster than the filter+indexOf idiom, which is O(n²).Why doesn't Set remove duplicate objects?
Does removing duplicates keep the order?
How do I remove duplicates but keep the first object, not the last?
for (const item of items) if (!map.has(item.id)) map.set(item.id, item);