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
const ROLE_PERMISSIONS = { admin: ['users:read', 'users:write', 'billing:read', 'billing:write'], manager: ['users:read', 'billing:read'], member: ['users:read'],
Role-based permissions middleware in Express
authorization
middleware
rbac
Intermediate
9 steps
ruby
class TemplateInterpolator PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/ def initialize(strict: false)
Interpolating templates with dotted keys in Ruby
regex
string-interpolation
hash-traversal
Intermediate
6 steps
javascript
function attachThousandSeparators(input, { locale = 'en-US' } = {}) { const formatter = new Intl.NumberFormat(locale); const groupSep = formatter.format(11111).replace(/\d/g, '')[0] || ','; const decimalSep = formatter.format(1.1).replace(/\d/g, '')[0] || '.';
Live thousand separators without losing the caret
dom
intl
caret-preservation
Advanced
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
javascript
import { useReducer, useEffect } from "react"; const initialState = { status: "idle", data: null, error: null };
Building a data-fetching hook in React
custom-hooks
usereducer
data-fetching
Intermediate
9 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.