Group Array Items by Key
Group an array of records into a map keyed by one of their fields, a building block for reports, indexes, and bucketed aggregations.
Code
export function groupBy(items, keyFn) {
const groups = new Map();
for (const item of items) {
const key = keyFn(item);
const bucket = groups.get(key);
if (bucket) {
bucket.push(item);
} else {
groups.set(key, [item]);
}
}
return groups;
}How it works
Count the function groupBy as the entire surface area of Group Array Items by Key.
Repetition is confined to for (const item of items) — the rest of the file is straight-line.
Applying it
Signature: export function groupBy(items, keyFn)
groupBy is what another module would consume; nothing else here is load-bearing for callers.
Statements that matter
const groups = new Map();
Interactive Tools for This Topic
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.Number FormatterFormat numbers with thousands grouping, fixed decimals, custom separators, and an optional prefix or suffix.Soundex EncoderEncode names into classic American Soundex codes with NARA rules for H/W separators, vowel boundaries, and zero padding.
FAQ
- Does this work in a bare project with no dependencies file?
- Yes — a bare project runs it as-is, since nothing needs declaring. The file defines `groupBy` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.