JavaScript Snippet

Flatten a Nested Array

Difficulty: Easy

Flattening a nested array is a one-line job most of the time, but pre-built `Array#flat` is shallow by default and the depth parameter has surprises. This snippet starts with the modern built-in, adds a recursive deep-flatten that works in any environment, and ends with the iterative stack version that avoids stack-overflow on pathological inputs. Three flavours, one mental model.

Code Snippets
/

Flatten a Nested Array

Flatten a Nested Array

Flattening a nested array is a one-line job most of the time, but pre-built `Array#flat` is shallow by default and the depth parameter has surprises. This snippet starts with the modern built-in, adds a recursive deep-flatten that works in any environment, and ends with the iterative stack version that avoids stack-overflow on pathological inputs. Three flavours, one mental model.

JavaScript
Easy
3 snippets
arrays
recursion
code-template
array-manipulation-patterns

410 views

4

Array.prototype.flat(depth) ships in every modern runtime (Node 11+, every evergreen browser). The default depth is 1, which is the most common gotcha. Pass Infinity for an unbounded deep flatten when you do not know how deep the nesting goes. Note that flat also drops sparse holes (skipping empty slots), which is usually the right behaviour for data pipelines but can surprise you if you rely on positional indexes.