More JavaScript answers

by Danny
Published 2 min read

Object.groupBy and Map.groupBy group array items by a key in one call, and are Baseline since 2024. Learn how to use them and the reduce fallback for older targets.

The short answer

#

Use Object.groupBy. Pass it the array and a function that returns the group key for each item. It returns an object with one property per key, each holding an array of the matching items.


_10
const orders = [
_10
{ id: 1, status: 'paid' },
_10
{ id: 2, status: 'pending' },
_10
{ id: 3, status: 'paid' },
_10
];
_10
_10
const byStatus = Object.groupBy(orders, (order) => order.status);
_10
// { paid: [order 1, order 3], pending: [order 2] }

Why it happens

#

Grouping is one of the most common data tasks: orders by status, posts by tag, events by day. For years JavaScript had no built-in for it, so most code used reduce or a utility library. Object.groupBy and Map.groupBy were added to the language to cover this directly.

They are Baseline as of 2024: supported in Chrome and Edge 117, Firefox 119 and Safari 17.4 and later, and in current Node.js LTS releases. If you support older browsers, use the reduce version below or a polyfill.

There are two versions because keys behave differently:

  • Object.groupBy turns each key into a string property name. Good for string keys, and easy to serialise as JSON.
  • Map.groupBy keeps keys as they are, so you can group by numbers, booleans, objects or dates without them being converted.

How to fix it

#

Object.groupBy for string keys

The callback receives each item and its index, and can compute a key rather than just read a property.


_11
const products = [
_11
{ name: 'Tea', price: 3 },
_11
{ name: 'Cake', price: 12 },
_11
{ name: 'Coffee', price: 4 },
_11
];
_11
_11
const byBand = Object.groupBy(products, (product) =>
_11
product.price < 5 ? 'budget' : 'premium',
_11
);
_11
_11
console.log(byBand.budget.map((p) => p.name)); // ['Tea', 'Coffee']

The returned object has a null prototype, so it does not inherit methods such as hasOwnProperty. Use Object.hasOwn or in to check for a group.

Map.groupBy for non-string keys

Use it when the key is an object or when you need to keep the key type.


_11
const teamA = { name: 'A' };
_11
const teamB = { name: 'B' };
_11
_11
const players = [
_11
{ name: 'Ada', team: teamA },
_11
{ name: 'Grace', team: teamB },
_11
{ name: 'Linus', team: teamA },
_11
];
_11
_11
const byTeam = Map.groupBy(players, (player) => player.team);
_11
console.log(byTeam.get(teamA).length); // 2

reduce for older environments

This produces the same shape as Object.groupBy and works everywhere.


_10
function groupBy(items, getKey) {
_10
return items.reduce((groups, item) => {
_10
const key = getKey(item);
_10
(groups[key] ??= []).push(item);
_10
return groups;
_10
}, {});
_10
}
_10
_10
const byStatus = groupBy(orders, (order) => order.status);

TypeScript

If TypeScript reports that groupBy does not exist, your lib setting is too old. Add ES2024 (or a later ESNext) to lib in tsconfig.json.


_10
{
_10
"compilerOptions": {
_10
"lib": ["ES2024", "DOM"]
_10
}
_10
}

Common pitfalls

#
  • Calling it as a method on the array, as in orders.groupBy(...). It is a static method: Object.groupBy(orders, fn).
  • Grouping by dates or numbers with Object.groupBy and expecting the original values back. Keys become strings; use Map.groupBy to keep them.
  • Assuming every group exists. Missing keys are simply absent, so byStatus.refunded can be undefined.
  • Mutating items after grouping. Groups hold references to the same objects, not copies.
#

Was this resource helpful?