Better solution ✅🚀
IntuitionThe task is to flatten an array to a specified depth:
If an element is an array and the current depth allows further flattening, expand that array into
# Intuition
The task is to flatten an array to a specified depth:

 - If an element is an array and the current depth allows further flattening, expand that array into its elements.
 - Otherwise, retain the element as is.

A stack-based approach provides an iterative alternative to recursion, allowing better control over depth and handling large arrays efficiently without risking a stack overflow.
# Approach
- **Initialize a Stack**:
    - Each stack entry contains an array element and its current depth.
    - Start by mapping all elements of the input array with the initial depth.
- **Iterate with a While Loop**:
    - Pop the top element from the stack.
    - If the element is an array and the depth is greater than 0:
        - Decompose the array into individual elements and push them back onto the stack with reduced depth.
    - Otherwise, add the element to the result array.
- **Reverse the Result**:
    - Since the stack operates in LIFO (Last-In-First-Out) order, the result is constructed in reverse.
    - Reverse the result array to obtain the correct order.
# Complexity
- Time complexity:
     - Each element is processed once, either as a primitive value or as part of an array.
    -  The total complexity is O(n), where n is the number of elements in the array, including all nested arrays.
- Space complexity:
  - The stack holds elements to be processed, which can grow up to 𝑂(𝑛) in the worst case.
  -  The result array also requires 𝑂(𝑛) space.
  - Overall: 𝑂(𝑛).
  
# Code
```javascript []
/**
 * @param {Array} arr
 * @param {number} depth
 * @return {Array}
 */
var flat = function(arr, depth) {
  const stack = [...arr.map(item => [item, depth])];
  const result = [];

  while (stack.length > 0) {
    const [item, depth] = stack.pop();

    if (Array.isArray(item) && depth > 0) {
      stack.push(...item.map(subItem => [subItem, depth - 1]));
    } else {
      result.push(item);
    }
  }

  return result.reverse();
};
```

![upvote pls.png](https://assets.leetcode.com/users/images/4a586ac3-7443-4b79-820e-cef7438c9a75_1737025581.3504028.png)

['JavaScript']