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

Expected output

[1, 2, 3, 4, 5]

Related snippets

Related DuskTools