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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Recursion naturally fits nested structures: handle one level, recurse on the rest.
  2. 2A depth counter that decrements toward a base case turns full recursion into bounded recursion.
  3. 3Spreading a recursive call's result lets you splice nested elements into a flat accumulator.

Related explainers

Share this explainer

Here's the card — post it anywhere.

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