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

snippet
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;
}