javascript / intermediate
Snippet
Partitioning Tabular Data Collections with Array Reduce
When displaying aggregated dashboard widgets in Angular components, data arrays often require grouping by specific status keys. Using Array.prototype.reduce transforms linear arrays into categorized dictionary partitions while maintaining strict type boundaries.
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
Breakdown
1
export type InventoryPartition = Record<InventoryItem['status'], InventoryItem[]>;
Constructs a mapped TypeScript record type guaranteeing every valid inventory status maps to an array.
2
return items.reduce<InventoryPartition>(
Executes an array reduction typed explicitly with the target categorized dictionary structure.
3
const { status } = currentItem;
Extracts the discriminant status key using ES6 destructuring assignment.
4
accumulator[status].push(currentItem);
Appends the current entity into its corresponding partition bucket inside the accumulator accumulator.
5
{ active: [], archived: [], pending: [] }
Supplies the initial state ensuring all categories are initialized with empty arrays.