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

typescript
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
import localeFrExtra from '@angular/common/locales/extra/fr';
import localeDe from '@angular/common/locales/de';

Locale-aware bootstrapping in Angular

i18n localization dependency-injection
Intermediate 8 steps
typescript
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import * as Joi from 'joi';
 

Validating env config at boot in NestJS

configuration schema-validation environment-variables
Intermediate 8 steps
javascript
function evaluate(expression) {
  const tokens = tokenize(expression);
  let pos = 0;
 

Building a recursive descent calculator

parsing recursion operator-precedence
Intermediate 8 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { InjectRepository } from '@nestjs/typeorm';

A cache-aside country lookup in NestJS

cache-aside dependency-injection batch-lookup
Intermediate 8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core';
 
interface Preferences {
  theme: 'light' | 'dark';

A signal-based preferences store in Angular

signals state-management persistence
Intermediate 7 steps
typescript
import { useEffect, useState } from "react";
 
interface Section {
  id: string;

Building a scroll-spy hook in React

custom-hooks intersectionobserver dom-observation
Intermediate 8 steps

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