#2625. Flatten Deeply Nested 
IntuitionWhen given a nested array and a depth, the task is to flatten the array up to the specified depth. Initially, it seems straightforward to iteratively o
# Intuition
When given a nested array and a depth, the task is to flatten the array up to the specified depth. Initially, it seems straightforward to iteratively or recursively traverse the array and unpack its elements based on the depth. The key challenge lies in properly handling nested arrays while respecting the depth constraint.

# Approach
1. **Recursive Flattening**:
   - Define a helper function that takes the current array and depth as parameters.
   - If the depth is 0, return the array as it is without further flattening.
   - Iterate through the array:
     - If an element is an array and the depth permits, recursively flatten it by decreasing the depth.
     - Otherwise, include the element in the result as-is.
2. **Base Case**:
   - Stop the recursion when the depth reaches 0 or when elements are no longer arrays.
3. **Result Construction**:
   - Use a temporary result array and the spread operator to unpack elements when flattening.
4. **Final Output**:
   - Return the fully or partially flattened array based on the given depth.

# Complexity
- **Time complexity**:
  - $$O(n)$$, where $$n$$ is the total number of elements in the array, including nested ones. Each element is visited once.

- **Space complexity**:
  - $$O(n)$$ in the worst case due to the recursive stack and storage for the flattened array.


# Code
```javascript []
/**
 * @param {Array} arr
 * @param {number} depth
 * @return {Array}
 */
var flat = function (arr, depth) {
    const flatten = (inputArray, currentDepth) => {
        if (currentDepth === 0) return inputArray;

        const result = [];
        for (const item of inputArray) {
            if (Array.isArray(item) && currentDepth > 0) {
                result.push(...flatten(item, currentDepth - 1));
            } else {
                result.push(item);
            }
        }
        return result;
    };

    return flatten(arr, depth);
};

/**
 * Example Usage:
 * console.log(flat([1, [2, [3, [4]]]], 2)); // [1, 2, 3, [4]]
 * console.log(flat([1, [2, [3, [4]]]], 1)); // [1, 2, [3, [4]]]
 * console.log(flat([1, [2, [3, [4]]]], 0)); // [1, [2, [3, [4]]]]
 */

```
['JavaScript']