JavaScript Interview Question #191
How would you remove duplicate objects from an array by a property?
Advanced JavaScript, Practical Problems & Senior Interview Scenarios Senior Advanced
Quick Interview Answer
A common solution is to use a Map keyed by the property that defines uniqueness. This makes the intended uniqueness rule explicit and can preserve either the first or last occurrence depending on how the algorithm is written.
Detailed Explanation
A common solution is to use a Map keyed by the property that defines uniqueness. This makes the intended uniqueness rule explicit and can preserve either the first or last occurrence depending on how the algorithm is written.
A Set works directly for primitive uniqueness, but separate object instances are unique by reference even when their properties contain the same values.
Code Example
const users = [
{ id: 1, name: "Ali" },
{ id: 2, name: "Asif" },
{ id: 1, name: "Ali Updated" }
];
const uniqueById = [
...new Map(
users.map(user => [user.id, user])
).values()
];
console.log(uniqueById);
// Last object for duplicate id wins.