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 { NestFactory } from '@nestjs/core'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import { ValidationPipe } from '@nestjs/common'; import { ApiProperty } from '@nestjs/swagger';
Wiring validation and Swagger docs in NestJS
validation
openapi
decorators
Intermediate
8 steps
typescript
import { Component, Input } from '@angular/core'; interface Order { id: string;
How Angular ICU plurals localize an order summary
i18n
pluralization
standalone-component
Intermediate
8 steps
java
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
Building a trie for autocomplete in Java
trie
prefix-tree
recursion
Intermediate
8 steps
ruby
class KeyTransformer def self.camelize(data) new.camelize(data) end
Recursively camelizing nested Ruby data
recursion
data-transformation
pattern-matching
Intermediate
7 steps
typescript
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common'; import { Observable, catchError, concatMap, finalize } from 'rxjs'; import { DataSource, QueryRunner } from 'typeorm';
Wrapping requests in a transaction with NestJS
interceptors
transactions
rxjs
Advanced
7 steps
typescript
type CsvColumn<T> = { header: string; value: (row: T) => string | number | boolean | null | undefined; };
Building a type-safe CSV writer in TypeScript
generics
serialization
escaping
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.