typescript 26 lines · 7 steps

Recursively flattening nested arrays in TypeScript

A recursive type and two functions that collapse arbitrarily nested arrays, either fully or to a chosen depth.

Explained by highlit
1type NestedArray<T> = Array<T | NestedArray<T>>;
2 
3function flatten<T>(input: NestedArray<T>): T[] {
4 const result: T[] = [];
5 for (const item of input) {
6 if (Array.isArray(item)) {
7 result.push(...flatten(item));
8 } else {
9 result.push(item);
10 }
11 }
12 return result;
13}
14 
15function flattenDepth<T>(input: NestedArray<T>, depth: number): NestedArray<T> {
16 if (depth <= 0) return input;
17 const result: NestedArray<T> = [];
18 for (const item of input) {
19 if (Array.isArray(item)) {
20 result.push(...flattenDepth(item, depth - 1));
21 } else {
22 result.push(item);
23 }
24 }
25 return result;
26}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A self-referential type alias lets the compiler describe data structures of unbounded nesting depth.
  2. 2Recursion mirrors the data's shape: descend into arrays, collect non-array values at each level.
  3. 3Passing a decrementing counter into the recursion turns 'flatten everything' into 'flatten N levels'.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Recursively flattening nested arrays in TypeScript — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code