Write a function uniqueBy(items, key) that removes duplicate objects based on a specified property.
Example:
const users = [
{ id: 1, name: "Alex" },
{ id: 2, name: "Sam" },
{ id: 1, name: "Alex Updated" },
{ id: 3, name: "John" }
];
uniqueBy(users, "id");
Expected result:
[
{ id: 1, name: "Alex" },
{ id: 2, name: "Sam" },
{ id: 3, name: "John" }
]
Rules:
-
Plain JavaScript, no libraries.
-
Do not mutate the original array.
-
Keep the first occurrence of each key.
-
Try to solve it in O(n) time.
How would you implement it?