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.

JavascriptData Integrity

Code

javascriptsnippet
13 lines
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

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.