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, 1By 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.comCommon 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, 1Functions used in this recipe
- Array.prototype.filter — Creates a new array from the elements that pass a test.
- Array.prototype.indexOf — Finds a value in an array and returns its index.
- Set — A collection of unique values.