Skip to content

2625. Flatten Deeply Nested Array 👍

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
type MultiDimensionalArray = (number | MultiDimensionalArray)[];

var flat = function (
  arr: MultiDimensionalArray,
  n: number
): MultiDimensionalArray {
  function dfs(arr: number | MultiDimensionalArray, n: number) {
    if (typeof arr === 'number') {
      ans.push(arr);
    } else if (n === 0) {
      for (const element of arr) {
        ans.push(element);
      }
    } else {
      for (const element of arr) {
        dfs(element, n - 1);
      }
    }
  }
  const ans: MultiDimensionalArray = [];
  dfs(arr, n);
  return ans;
};