How do you flatten a deeply nested array?
Flattening turns a nested array into a single-level array.
Built-in flat() — Array.prototype.flat(depth) flattens to a given depth; use Infinity for any nesting.
Recursion — loop items; if an item is an array, flatten it recursively, otherwise collect it.
reduce — combine reduce with recursion for a functional version.
Simplest modern choice: flat(Infinity) for arbitrary depth.
const nested = [1, [2, [3, [4, [5]]]], 6];
// Built-in flat() (recommended)
console.log(nested.flat()); // [1, 2, [3, [4, [5]]], 6] — depth 1
console.log(nested.flat(2)); // [1, 2, 3, [4, [5]], 6] — depth 2
console.log(nested.flat(Infinity)); // [1, 2, 3, 4, 5, 6] — all levels
// Recursive
function flattenRecursive(arr) {
return arr.reduce((flat, item) =>
flat.concat(Array.isArray(item) ? flattenRecursive(item) : item)
, []);
}
console.log(flattenRecursive(nested)); // [1, 2, 3, 4, 5, 6]
// Iterative (stack-based, no recursion limit)
function flattenIterative(arr) {
const stack = [...arr];
const result = [];
while (stack.length) {
const item = stack.pop();
if (Array.isArray(item)) {
stack.push(...item);
} else {
result.unshift(item);
}
}
return result;
}
// toString trick (only for numbers)
console.log(nested.toString().split(',').map(Number));
// [1, 2, 3, 4, 5, 6]flat(Infinity) is the built-in solution. The recursive approach uses reduce + concat: if the item is an array, flatten it recursively; otherwise, concat it directly.
The stack-based approach avoids recursion depth limits: pop items, push array contents back onto the stack, unshift non-arrays to maintain order. The toString trick works only for homogeneous numeric arrays.
flat(Infinity) is the quick answer. Show the recursive reduce implementation for depth.
The iterative stack approach for avoiding recursion limits is the advanced answer. Know that flat() is ES2019 — older environments need the manual implementations.