Flatten a multi-dimensional array

Flatten a multi-dimensional array in javascript with reduce and concat

// Flatten a multi-dimensional array
function flatArray(arrayToFlat) {
  return arrayToFlat.reduce( (flat, toFlatten) => {
    return flat.concat(Array.isArray(toFlatten) ? flatArray(toFlatten): toFlatten)
  }, []);
}

console.log(flatArray([[1],[2,3], [4], [5, [6,7,[8,9,[10]]]]])); // 1, 2, 3, 4,  5,6, 7, 8, 9, 10



//code for more info and understand better

// function flatArray(arrayToFlat) {
//   return arrayToFlat.reduce( (flat, toFlatten) => {
//     console.log("flat=>",flat)
//     let testData = flat.concat(Array.isArray(toFlatten) ? flatArray(toFlatten): toFlatten)
//     console.log("flatArray=>",testData)
//     return testData;
//   }, []);
  
// }
(Visited 15 times, 1 visits today)

Leave a comment

Your email address will not be published. Required fields are marked *