Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to find duplicates in an array

Short answer

An element is a duplicate if it was already seen earlier. Two Set objects store what was seen and what repeated:

const items = ['a', 'b', 'a', 'c', 'b', 'a'];
const seen = new Set();
const duplicates = new Set();
 
for (const item of items) {
  if (seen.has(item)) duplicates.add(item);
  seen.add(item);
}
 
console.log([...duplicates]);

Output:

[
  "a",
  "b"
]

With filter

A shorter way: keep the elements whose first position differs from the current one:

const items = [1, 2, 3, 2, 4, 1];
const duplicates = items.filter((item, index) => items.indexOf(item) !== index);
 
console.log([...new Set(duplicates)].join(', '));

Output:

2, 1

By an object field

For objects, compare the field that should be unique:

const users = [
  { email: 'anna@example.com' },
  { email: 'oleg@example.com' },
  { email: 'anna@example.com' },
];
const seen = new Set();
const repeated = users.filter((user) => seen.has(user.email) || !seen.add(user.email));
 
console.log(repeated.map((user) => user.email).join(', '));

Output:

anna@example.com

Common mistake

The filter() way without the final Set returns a value as many times as it repeats:

const items = [1, 1, 1];
 
console.log(items.filter((item, index) => items.indexOf(item) !== index).join(', '));

Output:

1, 1

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.