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
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
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
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
javascript
const { pool } = require('./db'); function withTransaction() { return async (req, res, next) => {
A per-request transaction middleware in Express
middleware
database-transactions
connection-pooling
Advanced
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.