How to collapse multidimensional array

Rus*_*yev 1 javascript recursion multidimensional-array

How to do that?

unpack_array([1, [10, 30, 40,[34,53],4],2]) -> [1,10,30,40,34,53,4,2]
Run Code Online (Sandbox Code Playgroud)

I know that recursion must be applied. I tried, but it turns out to work only in one direction.

function unpack_array (arr, acc_arr=[]) {
  if (!arr) return acc_arr;
  let i = 0;
  while (arr[i] && !Array.isArray(arr[i])) {
    acc_arr.push(arr[i++])
  }
  return unpack_array(arr[i], acc_arr)
}
Run Code Online (Sandbox Code Playgroud)

I believe that here need to use the "reduce" method.

cra*_*ash 5

The Array.prototype.flat() method will work, so long as you supply it with an argument of Infinity to ensure that all levels of the multidimensional array are flattened:

console.log([1, [10, 30, 40, [34, 53], 4], 2].flat(Infinity))
Run Code Online (Sandbox Code Playgroud)

As an alternative, the linked documentation suggests a recursive flatDeep method, which uses reduce and concat to implement the desired behaviour:

function flatDeep(arr) {
   return arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatDeep(val) : val), []);
};

console.log(flatDeep([1, [10, 30, 40, [34, 53], 4], 2]));
Run Code Online (Sandbox Code Playgroud)