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()];
}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
Duplicate Line RemoverFind unique, duplicate, or counted lines with optional case sensitivity and whitespace trimming, all processed locally in the browser.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.Soundex EncoderEncode names into classic American Soundex codes with NARA rules for H/W separators, vowel boundaries, and zero padding.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.