Deduplicate Arrays by Key Keeping First Item
Remove duplicate objects from an array using a key function or property name, preserving original order and first occurrences.
Code
export function uniqueBy(items, keyFn) {
if (!Array.isArray(items)) throw new TypeError("items must be an array");
if (typeof keyFn !== "function") throw new TypeError("keyFn must be a function");
const seen = new Set();
const result = [];
for (const item of items) {
const key = keyFn(item);
if (seen.has(key)) continue;
seen.add(key);
result.push(item);
}
return result;
}
export function uniqueByProperty(items, property) {
if (typeof property !== "string" || property.length === 0) {
throw new TypeError("property must be a non-empty string");
}
return uniqueBy(items, (item) => {
if (item === null || typeof item !== "object") {
throw new TypeError("items must contain objects");
}
return item[property];
});
}Report a problem with this exampleOpens a pre-filled issue on GitHub.