Dev Helpers

JavaScript / Arrays

Flatten nested arrays

Dev Helpers · January 3, 2026

Choose the flattening depth from the data contract. Flattening another level can erase a meaningful grouping.

Worked example

const data = [1, [2, [3, 4]]];
console.log(data.flat(Infinity));

Result

[ 1, 2, 3, 4 ]

Implementation notes

Flattening also interacts with sparse array slots. If holes carry application meaning, first convert them into explicit values so the transformation preserves that distinction.

Try it yourself

Add a nested pair two levels down and inspect which brackets remain.

Open the JavaScript example →

Editorial date January 3, 2026 · Published December 6, 2026

Related articles

Chunk an array

Batching work by array slices gives the last batch permission to be shorter. Guard the requested size before using it as the loop increment.

Remove duplicate values

Set preserves insertion order and collapses repeated primitive values. Objects still compare by reference.

Sum distances with a Euclidean norm

A diagonal is longer than either of its components. Math.hypot combines perpendicular distances without making the caller square each input.