Remove duplicates from an array

[...new Set(arr)] removes duplicate primitives in O(n) while keeping the first occurrence's order; for objects, deduplicate by a key with a Map or a Set of seen keys.

Primitives

  • [...new Set(arr)] or Array.from(new Set(arr)): the standard answer.
  • arr.filter((x, i) => arr.indexOf(x) === i): works but O(n²), and it drops NaN entirely because indexOf(NaN) is -1.
  • reduce with includes: also O(n²).

Set uses SameValueZero equality: NaN equals NaN, and 0 equals -0.

Objects

new Set([{id: 1}, {id: 1}]) keeps both, because objects are compared by reference. Choose what "duplicate" means:

  • By key, keep the first: track seen keys in a Set.
  • By key, keep the last (e.g. the latest update wins): [...new Map(arr.map(o => [o.id, o])).values()].
  • By several fields: build a composite key like `${o.name}|${o.email}`.
  • By full content: a stable JSON.stringify key (only for small, plain objects; key order matters).

Case-insensitive or normalised values

Deduplicate by a normalised key (email.trim().toLowerCase()) while keeping the original value.

Complexity

Set and Map approaches are O(n) time and O(n) space, and they preserve insertion order.

Code example

js
1const nums = [3, 1, 3, 2, 1, NaN, NaN, 0, -0];
2console.log([...new Set(nums)]); // [3, 1, 2, NaN, 0]
3console.log(nums.filter((x, i) => nums.indexOf(x) === i)); // [3, 1, 2, 0] - O(n^2), and NaN disappears!
4
5const users = [
6 { id: 1, name: "Ada", updated: 1 },
7 { id: 2, name: "Linus", updated: 1 },
8 { id: 1, name: "Ada L.", updated: 2 },
9];
10
11// By key, keep the FIRST occurrence
12function uniqueBy(items, keyFn) {
13 const seen = new Set();
14 return items.filter((item) => {
15 const key = keyFn(item);
16 if (seen.has(key)) return false;
17 seen.add(key);
18 return true;
19 });
20}
21console.log(uniqueBy(users, (u) => u.id).map((u) => u.name)); // ["Ada", "Linus"]
22
23// By key, keep the LAST occurrence (latest update wins)
24const latest = [...new Map(users.map((u) => [u.id, u])).values()];
25console.log(latest.map((u) => u.name)); // ["Ada L.", "Linus"]
26
27// Normalised comparison, original values kept
28const emails = ["Ada@Example.com", "ada@example.com ", "linus@example.com"];
29console.log(uniqueBy(emails, (e) => e.trim().toLowerCase())); // ["Ada@Example.com", "linus@example.com"]

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app