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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A self-referential type alias lets the compiler describe data structures of unbounded nesting depth.
- 2Recursion mirrors the data's shape: descend into arrays, collect non-array values at each level.
- 3Passing a decrementing counter into the recursion turns 'flatten everything' into 'flatten N levels'.
Related explainers
typescript
import { CallHandler, ExecutionContext, Injectable,
Wrapping responses in a NestJS interceptor
interceptors
rxjs
response-shaping
Intermediate
7 steps
typescript
type RetryOptions = { retries?: number; timeoutMs?: number; baseDelayMs?: number;
Retry with timeout and backoff in TypeScript
promises
retry
exponential-backoff
Intermediate
10 steps
python
from collections.abc import Mapping from typing import Any, Iterator
Flattening nested config into dotted keys
recursion
generators
tree-traversal
Intermediate
7 steps
typescript
import { Pipe, PipeTransform, ChangeDetectorRef, NgZone, OnDestroy } from '@angular/core'; @Pipe({ name: 'timeAgo',
A self-refreshing timeAgo pipe in Angular
impure-pipe
change-detection
timers
Advanced
10 steps
go
package cache import ( "container/list"
Building a generic LRU cache in Go
lru-cache
generics
linked-list
Intermediate
8 steps
typescript
const DIVISIONS: { amount: number; unit: Intl.RelativeTimeFormatUnit }[] = [ { amount: 60, unit: "seconds" }, { amount: 60, unit: "minutes" }, { amount: 24, unit: "hours" },
Human-readable relative times with Intl
internationalization
date-formatting
lookup-table
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/recursively-flattening-nested-arrays-in-typescript-explained-typescript-6fe3/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.