Skip to content
GreenSnippets

Group an array of objects by a key

Build an object of arrays keyed by a property or computed value, using Object.groupBy or a reduce fallback.

JavaScript
function groupBy(items, keyFn) {
  const groups = Object.create(null);
  for (const item of items) {
    const key = keyFn(item);
    (groups[key] ??= []).push(item);
  }
  return groups;
}

Example / expected output

Output
groupBy([{ n: "a", t: 1 }, { n: "b", t: 2 }, { n: "c", t: 1 }], (x) => x.t)
// { 1: [{n:"a",t:1}, {n:"c",t:1}], 2: [{n:"b",t:2}] }

How it works

Modern runtimes (Node 21+, current browsers) ship Object.groupBy. The fallback below works anywhere and keeps insertion order within each group. The result uses a null prototype so a key like "__proto__" from user data cannot pollute anything.