Deduplicate an Array by Key
Remove duplicate records that share a key, keeping the first or last occurrence so the result is deterministic and easy to reason about.
Code
export function dedupeBy(items, keyFn, keepLast = false) {
const seen = new Map();
for (const item of items) {
const key = keyFn(item);
if (!seen.has(key)) {
seen.set(key, item);
} else if (keepLast) {
seen.set(key, item);
}
}
return [...seen.values()];
}Report a problem with this exampleOpens a pre-filled issue on GitHub.