typescript / intermediate
Snippet
Transforming Nested Arrays Immutably with flatMap and Type Casting
Using flatMap allows simultaneous mapping and flattening of array fields. Wrapping the result in a Set removes duplicates in a single non-mutating pipeline typed with a readonly array modifier.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
type OrderItem = { id: string; tags: string[] };const orders: OrderItem[] = [{ id: 'o1', tags: ['urgent', 'tech'] },{ id: 'o2', tags: ['tech', 'clearance'] }];const uniqueTags: readonly string[] = Array.from(new Set(orders.flatMap(order => order.tags)));console.log(uniqueTags);
Breakdown
1
const uniqueTags: readonly string[] = Array.from(
Types the target array as an immutable readonly string array to prevent accidental mutations.
2
new Set(orders.flatMap(order => order.tags))
Extracts nested tag arrays, flattens them into a single array, and filters duplicates with Set.