Skip to content
Carl Victor Fontanos
Carl Victor Fontanos

Carl Victor Fontanos

Software Engineer

I build web applications and share what I learn along the way.

© 2026

Object.groupBy() Ends a Decade of reduce() Boilerplate

C
Carlo Fontanos
· 2 min read

I must have written this exact reduce() at least a hundred times: take an array of orders, group them by status. Every codebase has one, usually copy-pasted from the last project with the variable names half renamed.

const grouped = orders.reduce((acc, order) => {
    (acc[order.status] ??= []).push(order);
    return acc;
}, {});

It works, but nobody reads it at a glance. Since 2024 the language just does this:

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

// {
//   paid: [{...}, {...}],
//   pending: [{...}],
//   refunded: [{...}]
// }

The Map version is the one you actually want

Object.groupBy() has a sibling, Map.groupBy(), and it matters which one you pick. Object keys get coerced to strings, so grouping by anything that isn't a string gets weird fast. Map keys stay whatever they are, including objects:

// Group order items by their product object, not a string id
const byProduct = Map.groupBy(items, item => item.product);

for (const [product, productItems] of byProduct) {
    console.log(product.name, productItems.length);
}

That last loop is the payoff: you iterate real product objects, no lookups back into another array.

One gotcha worth knowing

The object returned by Object.groupBy() is a null-prototype object. That's a deliberate safety feature (no inherited keys like constructor sneaking into your groups), but it means grouped.hasOwnProperty() throws. Use Object.hasOwn(grouped, key) or the in operator instead.

Support

All evergreen browsers have shipped it: Chrome 117+, Firefox 119+, Safari 17.4+. Node.js has it from version 21. If you need to support anything older, keep the reduce() around, but for new projects there's no reason to write grouping by hand anymore.

Small feature, but it deletes real code from almost every app I work on. The related array_column() tricks in PHP scratch a similar itch on the backend.

C
Written by Carlo Fontanos

Full-stack web developer sharing practical tutorials and building tools that ship.

Got something on your mind?

My inbox is open - no forms disappearing into the void here.

  • Just say hello Found a tutorial useful? Spotted a mistake? Tell me.
  • Hire me for a project Have something custom in mind? Let's talk scope and timelines.
  • Product support Bought something here? I'll help you get it running.

I usually reply within 1-2 business days.

Message sent!

Your details are only used to reply to you.

Keep reading