Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to remove duplicates from an array

Short answer

A Set holds only unique values. Turn the array into a Set and back:

console.log([...new Set([1, 2, 2, 3, 1])].join(', '));

Output:

1, 2, 3

An array of objects

Objects are compared by reference, so Set does not help. Keep the first object with each id:

const users = [
  { id: 1, name: 'Anna' },
  { id: 2, name: 'Oleg' },
  { id: 1, name: 'Anna' },
];
const unique = users.filter(
  (user, index) => users.findIndex((other) => other.id === user.id) === index,
);
 
console.log(unique.map((user) => user.name).join(', '));

Output:

Anna, Oleg

Ignoring case

To treat Anna and anna as the same, compare normalized values:

const names = ['Anna', 'anna', 'Oleg', 'ANNA'];
const seen = new Set();
const unique = names.filter((name) => {
  const key = name.toLowerCase();
  if (seen.has(key)) return false;
  seen.add(key);
  return true;
});
 
console.log(unique.join(', '));

Output:

Anna, Oleg

Common mistake

Set treats the number 1 and the string '1' as different values. Convert the values to one type first:

const ids = [1, '1', 2, '2'];
 
console.log([...new Set(ids)].length);
console.log([...new Set(ids.map(Number))].length);

Output:

4
2

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.