How to remove duplicate objects by a field
Short answer
Keep the first object with each value of the field, remembering seen values in a Set:
const users = [
{ id: 1, name: 'Anna' },
{ id: 2, name: 'Oleg' },
{ id: 1, name: 'Anna (copy)' },
];
const seen = new Set();
const unique = users.filter((user) => {
if (seen.has(user.id)) return false;
seen.add(user.id);
return true;
});
console.log(unique.map((user) => user.name).join(', '));Output:
Anna, OlegKeep the last one
A Map with the field as the key overwrites earlier objects, so the last one wins:
const users = [
{ id: 1, name: 'Anna' },
{ id: 2, name: 'Oleg' },
{ id: 1, name: 'Anna (updated)' },
];
const unique = [...new Map(users.map((user) => [user.id, user])).values()];
console.log(unique.map((user) => user.name).join(', '));Output:
Anna (updated), OlegCommon mistake
new Set() does not help with objects directly: it compares them by reference, and different objects are always different:
const users = [{ id: 1 }, { id: 1 }];
console.log(new Set(users).size);Output:
2Functions used in this recipe
- Map — A collection of key–value pairs where a key can be anything.
- Array.prototype.filter — Creates a new array from the elements that pass a test.
- Set — A collection of unique values.