Solution

Algorithm

  • Let's create a recursive function.
  • Let's write a base case for recursion: if depth is equal to 0, then just return given array
  • Iterate over a given array and on every step of iteration check whether the current item is an array or no
    • If it's an array, then flat it with the spread operator and call the recursive function with the current item
    • If it's not an array, then just push it to result array
  • Return result

Recursive Solution

Use recursion to flatten by one level per call until depth is 0:

function flat(arr, depth = 1) {
  if (depth === 0) return arr;
  const result = [];
  for (const item of arr) {
    if (Array.isArray(item)) {
      result.push(...flat(item, depth - 1));
    } else {
      result.push(item);
    }
  }
  return result;
}
  • Time complexity: O(n), where n is total number of elements including nested.
  • Space complexity: O(depth) for the call stack.