Remove Duplicates from an Array in JavaScript
Deduplicate an array by passing it through a Set and spreading it back to an array.
Also known as: JS unique array, dedupe array JavaScript
beginner
[...new Set(arr)] builds a Set (which rejects duplicates) then spreads it back into an array, preserving first-seen order for primitive values.
What it is
A Set stores only unique values, so constructing one from an array drops duplicates. Spreading it back with [...new Set(arr)] returns a plain array, keeping the order in which each value first appeared. This is the shortest correct approach for primitives (numbers, strings, booleans).
Set uses SameValueZero equality, so it treats NaN as equal to NaN (unlike ===) and distinguishes 0 from -0 as equal. For objects, identity is by reference, so two different objects with equal contents are not deduped.
Worked example
const nums = [1, 2, 2, 3, 3, 3];
const unique = [...new Set(nums)];
console.log(unique); // [1, 2, 3]
// De-dupe objects by a key
const users = [{ id: 1 }, { id: 1 }, { id: 2 }];
const byId = [...new Map(users.map((u) => [u.id, u])).values()];
console.log(byId); // [{ id: 1 }, { id: 2 }]
Failure mode — when it misleads
new Set only dedupes primitives by value; arrays of objects won't collapse because each object is a distinct reference. To dedupe objects, key them (e.g. with a Map keyed on an id, as above) or compare a serialized form — but note JSON.stringify is order-sensitive and can miss logically-equal objects with different key orders.
Related entries
Sources & further reading
- Set (MDN) (article)