Turn an arbitrarily nested array like [1, [2, [3, [4]]]] into a flat [1, 2, 3, 4].
Modern JS has Array.prototype.flat(depth). For arbitrary depth use flat(Infinity). To implement it yourself, use recursion or a stack; reduce with concat is the classic recursive one-liner.
const flatten = (arr) => arr.flat(Infinity);
// Manual recursive implementation:
function flattenDeep(arr) {
return arr.reduce(
(acc, x) => acc.concat(Array.isArray(x) ? flattenDeep(x) : x),
[]
);
}Flattening is common when normalizing nested API responses (e.g. categories with sub-categories) into a single list for a test assertion.
flattenDeep crashes with 'Maximum call stack size exceeded' on a 100,000-deep nested array. How do you fix it?