How do you remove duplicates from an array in JavaScript?

← JavaScript answers

Pass the array through a Set and spread it back into an array: [...new Set(items)].

A Set stores each value once, so converting an array to a Set and back removes duplicates while keeping the first occurrence of each value in order.

const ids = [3, 1, 3, 2, 1];
const unique = [...new Set(ids)]; // [3, 1, 2]

A Set compares objects by reference, so it will not merge two objects that merely look the same. To deduplicate objects by a field, keep one entry per key in a Map:

const users = [
  { id: 1, name: "Ada" },
  { id: 2, name: "Linus" },
  { id: 1, name: "Ada (copy)" },
];
 
const uniqueUsers = [...new Map(users.map((u) => [u.id, u])).values()];
// later entries win; reverse the array first if you want the first one to win

Related questions

Start debugging smarter today

Try Bugsee for free — no commitments, no hidden fees.

Free sign upLive demoNo credit card required