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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Accepting either a key name or a selector function makes one utility fit many callers.
- 2reduce with an object accumulator is a clean pattern for bucketing items by a derived key.
- 3The ??= operator lazily initializes a bucket only the first time a key appears.
Related explainers
javascript
const ROLE_PERMISSIONS = { admin: ['users:read', 'users:write', 'billing:read', 'billing:write'], manager: ['users:read', 'billing:read'], member: ['users:read'],
Role-based permissions middleware in Express
authorization
middleware
rbac
Intermediate
9 steps
ruby
class TemplateInterpolator PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/ def initialize(strict: false)
Interpolating templates with dotted keys in Ruby
regex
string-interpolation
hash-traversal
Intermediate
6 steps
javascript
function attachThousandSeparators(input, { locale = 'en-US' } = {}) { const formatter = new Intl.NumberFormat(locale); const groupSep = formatter.format(11111).replace(/\d/g, '')[0] || ','; const decimalSep = formatter.format(1.1).replace(/\d/g, '')[0] || '.';
Live thousand separators without losing the caret
dom
intl
caret-preservation
Advanced
8 steps
ruby
class KeyTransformer def self.camelize(data) new.camelize(data) end
Recursively camelizing nested Ruby data
recursion
data-transformation
pattern-matching
Intermediate
7 steps
javascript
import { useReducer, useEffect } from "react"; const initialState = { status: "idle", data: null, error: null };
Building a data-fetching hook in React
custom-hooks
usereducer
data-fetching
Intermediate
9 steps
typescript
type CsvColumn<T> = { header: string; value: (row: T) => string | number | boolean | null | undefined; };
Building a type-safe CSV writer in TypeScript
generics
serialization
escaping
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-flexible-groupby-in-javascript-explained-javascript-60d8/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.