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

javascriptsnippet
12 lines
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()];
}

What the code does

Count the function dedupeBy as the entire surface area of Deduplicate an Array by Key.

Repetition is confined to for (const item of items) — the rest of the file is straight-line.

What comes back is a new object, not a reference to anything passed in.

Applying it

Entry signature: export function dedupeBy(items, keyFn, keepLast = false)

dedupeBy is the public entry point; everything else in the file exists to support it.

Statements that matter

return [...seen.values()];
const seen = new Map();

Interactive Tools for This Topic

FAQ

Does `dedupeBy` modify its input?
No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
Is there an install step between copy and run?
No. Between copying and running there is nothing left to do. The file defines `dedupeBy` at load time.