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.

JavascriptData Integrity

Code

snippet
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()];
}