JavaScript program that flattens an array of arbitrarily nested arrays of integers into a flat array of integers
Posted by SceDev
Last Updated: March 10, 2024

Write a JavaScript program that flattens an array of arbitrarily nested arrays of integers into a flat array of integers.

Code:

function flatten(arr) {
    return arr.reduce((y, x) => Array.isArray(x) ? y.concat(flatten(x)) : y.concat(x), []);
  }

var result = flatten([1, [2, [3, [4]], 5], [6]]) 
console.log(result);