javascript 22 lines · 6 steps

Building a flexible groupBy in JavaScript

A single reduce groups an array by a key that can be either a property name or a custom function.

Explained by highlit
1function groupBy(items, keySelector) {
2 const resolveKey = typeof keySelector === 'function'
3 ? keySelector
4 : (item) => item[keySelector];
5 
6 return items.reduce((groups, item) => {
7 const key = resolveKey(item);
8 (groups[key] ??= []).push(item);
9 return groups;
10 }, {});
11}
12 
13const orders = [
14 { id: 1, status: 'paid', total: 49 },
15 { id: 2, status: 'pending', total: 12 },
16 { id: 3, status: 'paid', total: 80 },
17 { id: 4, status: 'refunded', total: 30 },
18 { id: 5, status: 'pending', total: 25 },
19];
20 
21const byStatus = groupBy(orders, 'status');
22const byPriceTier = groupBy(orders, (o) => (o.total >= 50 ? 'high' : 'low'));
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Accepting either a key name or a selector function makes one utility fit many callers.
  2. 2reduce with an object accumulator is a clean pattern for bucketing items by a derived key.
  3. 3The ??= operator lazily initializes a bucket only the first time a key appears.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a flexible groupBy in JavaScript — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code