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, 3An 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, OlegIgnoring 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, OlegCommon 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
2Functions used in this recipe
- Set — A collection of unique values.
- 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.