JavaScript Object.groupBy

Group Array Items by Key


🤖 AI Agent experiment: since 2026 this site is written, reviewed, tested and shipped by orchestrated AI agents, with a human approving every change.

Grouping array items into named buckets was always a job for reduce, with an accumulator object and a check for whether each key already existed before pushing into it. Object.groupBy does that in one call now, and the result reads a lot closer to what you actually meant.

We will look at how Object.groupBy works with a simple example first, and then use it to replace a reduce call that used to take a few more lines to get right.

How it Works

Object.groupBy takes an array and a callback that returns the key for each item, and gives back a plain object where each key holds the array of items that matched it.

const people = [
  { name: "Ana", age: 25 },
  { name: "Bruno", age: 17 },
  { name: "Carla", age: 34 },
]

const byAgeGroup = Object.groupBy(people, person =>
  person.age >= 18 ? "adults" : "minors"
)

console.log(byAgeGroup)
// { adults: [{name: "Ana", age: 25}, {name: "Carla", age: 34}], minors: [{name: "Bruno", age: 17}] }

We pass a callback that checks the age field of each person and returns "adults" or "minors" as the group name. Object.groupBy runs that callback once per item and builds the object for us, no accumulator to set up and no branching logic to keep track of by hand.

Replacing a reduce call

Before this landed, grouping meant writing a reduce with an initial value and pushing into an array that might not exist yet on the accumulator.

const orders = [
  { id: 1, status: "paid" },
  { id: 2, status: "pending" },
  { id: 3, status: "paid" },
]

const byStatus = Object.groupBy(orders, order => order.status)

console.log(Object.keys(byStatus)) // ["paid", "pending"]
console.log(byStatus.paid.length) // 2

The old reduce version needed a check for whether the accumulator already had that key before pushing, otherwise it would throw on the first item of each group. Object.groupBy handles that for us, and the result comes back as a plain object we can read with Object.keys or destructure directly.

Conclusion

Object.groupBy will not remove reduce from your toolbox, there are still plenty of aggregations it cannot express this way. But for the specific job of splitting an array into named buckets, it reads clearer than the reduce version and there is one less thing to get wrong. Worth checking your target browsers and Node version support it before you rely on it in production code.

Have a nice code!

Comments