Flatten an arbitrarily nested array
Implement flatten(arr) that returns a single-level array containing every non-array value from arr, no matter how deeply nested, in order. flatten([1, [2, [3, [4]], 5]]) returns [1, 2, 3, 4, 5]. Do not use the built-in Array.prototype.flat(Infinity).
function flatten(arr) {
// your code here
}
Write the implementation.
Iterate the array with reduce; for each element, if Array.isArray is true, recurse into it and concat the flattened result, otherwise push the value. The recursion is what reaches every depth. An empty array reduces to [], and the order of elements is preserved across all levels.
- ✗Flattening only one level (a bare
concat) and missing deeper nesting - ✗Checking
typeof x === 'object'instead ofArray.isArray, mishandling nulls and objects - ✗Mutating the input array while recursing instead of building a new one
- →How would you flatten to only a fixed depth
ninstead of all the way down? - →Why is
Array.isArraysafer thaninstanceof Arrayacross realms?
Solution
Fold the array with reduce, recursing into every nested array.
function flatten(arr) {
return arr.reduce(
(acc, item) =>
Array.isArray(item) ? acc.concat(flatten(item)) : acc.concat(item),
[]
);
}
How it works
reduce accumulates the flat result in acc. For each element we check Array.isArray: if it is an array, recurse to flatten it and concat the result; otherwise just push the value. The recursion reaches values at any depth, and order is preserved because elements are processed left to right.
An empty array immediately reduces to the initial []. A new array is built from scratch, so the input is never mutated. </content>