javascript
23 lines · 7 steps
Flattening nested arrays with recursion
Two recursive takes on flattening arrays: one fully, one with a depth limit.
Explained by
highlit
1function flatten(arr) {
2 const result = [];
3 for (const item of arr) {
4 if (Array.isArray(item)) {
5 result.push(...flatten(item));
6 } else {
7 result.push(item);
8 }
9 }
10 return result;
11}
12
13function flattenDepth(arr, depth = Infinity) {
14 if (depth < 1) return arr.slice();
15 return arr.reduce((acc, item) => {
16 if (Array.isArray(item)) {
17 acc.push(...flattenDepth(item, depth - 1));
18 } else {
19 acc.push(item);
20 }
21 return acc;
22 }, []);
23}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Recursion naturally fits nested structures: handle one level, recurse on the rest.
- 2A depth counter that decrements toward a base case turns full recursion into bounded recursion.
- 3Spreading a recursive call's result lets you splice nested elements into a flat accumulator.
Related explainers
javascript
'use server' import { revalidatePath } from 'next/cache' import { redirect } from 'next/navigation'
How a Next.js Server Action updates a post
server-actions
authorization
validation
Intermediate
7 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
javascript
const express = require('express'); const v1 = express.Router();
Versioning an API with Express Routers
api versioning
routing
modularity
Intermediate
10 steps
java
public class SortedListMerger { public static int[] merge(int[] a, int[] b) { int[] result = new int[a.length + b.length];
Merging two sorted arrays in Java
two-pointers
merging
arrays
Beginner
6 steps
javascript
const RATE_LIMIT = 100; const WINDOW_MS = 60 * 1000; const BLOCK_MS = 5 * 60 * 1000;
Building a rate-limiting middleware in Express
rate-limiting
middleware
closures
Intermediate
9 steps
ruby
require 'json' require 'set' class SensitiveScrubber
Recursively scrubbing secrets from JSON
recursion
data-masking
pattern-matching
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/flattening-nested-arrays-with-recursion-explained-javascript-f0d8/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.