Object.groupBy And Map.groupBy Bucketing

Bucket records with Object.groupBy for string keys and Map.groupBy for arbitrary keys, replacing hand-rolled reduce accumulation without touching the source.

TypescriptData Integrity

Code

typescriptsnippet
25 lines
// Object.groupBy / Map.groupBy (ES2024): 一次遍历分桶,源数组不动
interface Ticket {
  id: number;
  severity: 'low' | 'high';
  hours: number;
}

const tickets: Ticket[] = [
  { id: 1, severity: 'low', hours: 2 },
  { id: 2, severity: 'high', hours: 9 },
  { id: 3, severity: 'high', hours: 4 },
  { id: 4, severity: 'low', hours: 1 },
];

// Object.groupBy:键只能是字符串,返回 Partial<Record<severity, Ticket[]>>
const bySeverity = Object.groupBy(tickets, (t) => t.severity);
for (const [severity, group] of Object.entries(bySeverity)) {
  const total = (group ?? []).reduce((sum, t) => sum + t.hours, 0);
  console.log(`${severity}: ${group?.length ?? 0} tickets / ${total}h`);
}

// Map.groupBy:键可以是任意类型(布尔、数字、对象都行)
const overdue = Map.groupBy(tickets, (t) => t.hours >= 4);
console.log(`overdue=${overdue.get(true)?.length} normal=${overdue.get(false)?.length}`);
console.log('source intact:', tickets.length);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

low: 2 tickets / 3h
high: 2 tickets / 13h
overdue=2 normal=2
source intact: 4

How it works

Everything happens inside the function total.

Repetition is confined to for (const [severity, group] of Object.entries(bySeverity)) — the rest of the file is straight-line.

Putting it to use

The main signature reads const total = (group ?? [])

The demo output is labeled (source intact:), so every printed line traces back to the operation that produced it.

Core lines

const total = (group ?? []).reduce((sum, t) => sum + t.hours, 0);
const bySeverity = Object.groupBy(tickets, (t) => t.severity);
const overdue = Map.groupBy(tickets, (t) => t.hours >= 4);

Interactive Tools for This Topic

FAQ

Are there any imports to resolve outside the language?
No. Every import resolves against the language's own modules. The file defines `total` at load time.