Flatten Array
Flatten nested arrays using flat() or recursion.
Code
JavaScript
// One level: flat()
const arr = [1, [2, 3], [4, 5]];
console.log(arr.flat()); // [1, 2, 3, 4, 5]
// Any depth: flat(Infinity)
const nested = [1, [2, [3, [4]]]];
console.log(nested.flat(Infinity)); // [1, 2, 3, 4]
// Recursive
function flatten(arr) {
return arr.reduce((acc, x) =>
Array.isArray(x) ? acc.concat(flatten(x)) : acc.concat(x), []);
}Line-by-line explanation
- 1.flat() with no arg flattens one level.
- 2.flat(Infinity) flattens to any depth.
- 3.Recursive reduce handles arbitrary nesting.
Expected output
[1, 2, 3, 4, 5]