typescript 28 lines · 6 steps

A type-safe groupBy in TypeScript

A generic helper that buckets items by any computed key, with the return type inferred from the key function.

Explained by highlit
1interface Order {
2 id: number;
3 customerId: string;
4 total: number;
5 status: 'pending' | 'shipped' | 'delivered';
6}
7 
8function groupBy<T, K extends PropertyKey>(
9 items: readonly T[],
10 keyFn: (item: T) => K,
11): Record<K, T[]> {
12 return items.reduce((groups, item) => {
13 const key = keyFn(item);
14 (groups[key] ??= []).push(item);
15 return groups;
16 }, {} as Record<K, T[]>);
17}
18 
19const ordersByStatus = groupBy(orders, (order) => order.status);
20const ordersByCustomer = groupBy(orders, (order) => order.customerId);
21 
22const revenueByCustomer = Object.entries(ordersByCustomer).map(
23 ([customerId, customerOrders]) => ({
24 customerId,
25 orderCount: customerOrders.length,
26 revenue: customerOrders.reduce((sum, o) => sum + o.total, 0),
27 }),
28);
01 / 01
STEP 01

Walkthrough

Space play ←→ step click any line
Three takeaways
  1. 1Generic type parameters let one function stay reusable while preserving precise types at every call site.
  2. 2reduce with a typed accumulator turns a flat list into a keyed structure in a single pass.
  3. 3Once data is grouped, Object.entries plus map is a clean route to per-key aggregates.

Related explainers

typescript
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
import localeFrExtra from '@angular/common/locales/extra/fr';
import localeDe from '@angular/common/locales/de';

Locale-aware bootstrapping in Angular

i18n localization dependency-injection
Intermediate 8 steps
typescript
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import * as Joi from 'joi';
 

Validating env config at boot in NestJS

configuration schema-validation environment-variables
Intermediate 8 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { InjectRepository } from '@nestjs/typeorm';

A cache-aside country lookup in NestJS

cache-aside dependency-injection batch-lookup
Intermediate 8 steps
ruby
class LogAggregator
  BUCKET_FORMAT = "%Y-%m-%dT%H:%M"
 
  def initialize(entries)

Bucketing log entries by the minute in Ruby

aggregation hashing enumerable
Intermediate 5 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core';
 
interface Preferences {
  theme: 'light' | 'dark';

A signal-based preferences store in Angular

signals state-management persistence
Intermediate 7 steps
ruby
class WeeklySignupsReport
  DEFAULT_WEEKS = 12
 
  def initialize(weeks: DEFAULT_WEEKS, source: User.all)

Building a weekly signups report in Rails

service object aggregation group by
Intermediate 7 steps

Share this explainer

Here's the card — post it anywhere.

A type-safe groupBy in TypeScript — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code