0 Tage Serie
javascript / intermediate
Snippet

Partitionierung tabellarischer Datenmengen mittels Array-Reduce

Bei der Anzeige aggregierter Dashboard-Elemente in Angular-Komponenten müssen Daten-Arrays häufig nach Statuswerten gruppiert werden. Array.prototype.reduce transformiert lineare Arrays in kategorisierte Objektstrukturen bei voller Wahrung der statischen Typsicherheit.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
export interface InventoryItem {
id: number;
name: string;
status: 'active' | 'archived' | 'pending';
quantity: number;
}
export type InventoryPartition = Record<InventoryItem['status'], InventoryItem[]>;
export function partitionInventory(items: InventoryItem[]): InventoryPartition {
return items.reduce<InventoryPartition>(
(accumulator, currentItem) => {
const { status } = currentItem;
if (!accumulator[status]) {
accumulator[status] = [];
}
accumulator[status].push(currentItem);
return accumulator;
},
{ active: [], archived: [], pending: [] }
);
}
angular
Erklärung
1
export type InventoryPartition = Record<InventoryItem['status'], InventoryItem[]>;
Erstellt einen Record-Typ, der sicherstellt, dass jeder Statuswert auf ein Array abgebildet wird.
2
return items.reduce<InventoryPartition>(
Führt eine Array-Reduktion aus, die explizit auf die Zielstruktur typisiert ist.
3
const { status } = currentItem;
Extrahiert den Status-Schlüssel mittels ES6-Destrukturierung.
4
accumulator[status].push(currentItem);
Fügt das aktuelle Element dem passenden Kategorie-Array im Akkumulator hinzu.
5
{ active: [], archived: [], pending: [] }
Definiert den Startwert, sodass alle Statuskategorien mit leeren Arrays vorinitialisiert sind.