Efficiently Flatten Deeply Nested Arrays with Controlled Depth
IntuitionThe idea is to iteratively flatten the array up to the given depth. We use a while loop to control the depth and a nested while loop to traverse the ar
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The idea is to iteratively flatten the array up to the given depth. We use a while loop to control the depth and a nested while loop to traverse the array and flatten it.

# Approach
<!-- Describe your approach to solving the problem. -->
1. Use a while loop to control the depth of flattening.
2. Within the loop, traverse the array and check if any element is an array.
3. If an element is an array, flatten it by using splice and spread operator.
4. If no elements are arrays, break the loop.
5. Decrease the depth after each iteration.

# Complexity
- Time complexity O(n * d): Where n is the number of elements in the array and d is the depth. In the worst case, we might need to traverse the entire array d times.

- Space complexity O(1): We are modifying the array in place, so no extra space is used.
<!-- Add your space complexity here, e.g. $$O(n)$$ -->


# Code
```javascript []
const flat = (array, depth) => {
  while (depth) {
    let isFlattened = true;

    let len = array.length;
    let i = 0;
    while (i < len) {
      if (Array.isArray(array[i])) {
        const currentLen = array[i].length;
        array.splice(i, 1, ...array[i]);
        i = i + currentLen - 1;
        len = array.length;
        isFlattened = false;
      }

      
      i++;
    }
    
    if (isFlattened) {
      break;
    }
    depth--;
  }

  return array;
};
```
['JavaScript']