The Set method (best for primitives)

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

This works perfectly for numbers, strings, and other primitive values, and it keeps the first appearance of each item.

Using filter() and indexOf()

const nums = [1, 2, 2, 3];
const unique = nums.filter((value, index) => nums.indexOf(value) === index);
console.log(unique);  // [1, 2, 3]

indexOf returns the first position of a value, so the test only keeps each item the first time it appears.

Removing duplicate objects by a key

const users = [{ id: 1 }, { id: 2 }, { id: 1 }];
const seen = new Set();
const unique = users.filter((u) => {
  if (seen.has(u.id)) return false;
  seen.add(u.id);
  return true;
});

Objects are compared by reference, so a Set alone will not dedupe them — track a key such as id instead.

Which method should you use?

  • [...new Set(arr)] — the go-to for primitive values.
  • filter + seen set — when you need to dedupe objects by a property.
  • Common mistake: expecting a plain Set to remove duplicate objects — it compares references, not contents.

Frequently asked questions

Does the Set method keep the original order?

Yes. A Set remembers insertion order, so [...new Set(arr)] keeps the first occurrence of each value in its original position.

How do I remove duplicate objects?

Objects are unique by reference, so filter while tracking a key (like id) in a Set to detect repeats.

New to Set and array methods? Build a solid base with our free JavaScript course.