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
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
javascript
const { pool } = require('./db'); function withTransaction() { return async (req, res, next) => {
A per-request transaction middleware in Express
middleware
database-transactions
connection-pooling
Advanced
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.