How-To

How-To · Arrays

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.

XCODXHow-To · Updated

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?
For primitives, [...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?
Objects are compared by reference, so two separate object literals are never considered equal — a Set keeps both. De-duplicate objects by a unique field using a Map keyed on that field.
Does removing duplicates keep the order?
Yes. Both the Set method and the filter+indexOf idiom preserve the order of first appearance. A Map keyed by id keeps items in first-seen key order but retains the last value for each key.
How do I remove duplicates but keep the first object, not the last?
Iterate and only set a key if the Map doesn't already have it: for (const item of items) if (!map.has(item.id)) map.set(item.id, item);