2625. Flatten Deeply Nested Array Solution
IntuitionThis problem is about flattening nested arrays to a given depth n. It tests our understanding of recursion, array traversal, and conditional logic base
# **Intuition**

This problem is about **flattening nested arrays** to a given depth `n`. It tests our understanding of **recursion**, **array traversal**, and **conditional logic based on depth**.

Flattening means converting nested arrays into a single-level array, but only up to `n` levels deep. If `n = 0`, we return the array as-is. If `n > 0`, we go deeper into each sub-array recursively.

---

# **Understanding Flattening with Depth**

✅ **What is Flattening?**  
Flattening is the process of reducing the depth of nested arrays into a simpler, single-dimensional structure.

✅ **What is Depth-limited Flattening?**  
Instead of completely flattening the array, we **only flatten `n` levels** deep. Each recursive level reduces `n` by 1, and stops when `n === 0`.

🔹 **Example:**

```js
Input: arr = [1,[2],[3,[4]]], n = 1  
Output: [1,2,3,[4]]
```

---

# **Approach**

I explored a **recursive depth-first approach** that reduces `n` on each nested call. If the current element is an array and depth allows (`n > 0`), I flatten it recursively. Otherwise, I push the element as-is.

---

# 🔹 **Approach: Recursive Flattening with Depth Check**

```js
var flat = function (arr, n) {
    let newArr = [];

    if (n === 0) return arr;

    arr.forEach((ele) => {
        if (Array.isArray(ele)) {
            newArr.push(...flat(ele, n - 1));
        } else {
            newArr.push(ele);
        }
    });

    return newArr;
};
```

📌 **Explanation:**

- We loop over each element in the array.
- If the element is an array and `n > 0`, we recursively call `flat()` and spread its result.
- If it’s not an array or `n` is 0, we push it directly.
- `n` is decreased each time we go one level deeper.

✅ **Pros:**

- Simple and elegant.
- Avoids unnecessary loops with recursion.
- Fully respects the depth `n`.

---

# **Complexity Analysis**

- **Time Complexity:**
  - $$O(m)$$ – where `m` is the total number of elements (including nested).
- **Space Complexity:**
  - $$O(m)$$ – due to the new array and recursive call stack.

---

# **Code Implementation**

```js
/**
 * @param {any[]} arr
 * @param {number} n
 * @return {any[]}
 */

var flat = function (arr, n) {
    let newArr = [];

    if (n === 0) return arr;

    arr.forEach((ele) => {
        if (Array.isArray(ele)) {
            newArr.push(...flat(ele, n - 1));
        } else {
            newArr.push(ele);
        }
    });

    return newArr;
};
```

---

# **Important Topics to Learn 📚**

- **Recursion**: Breaking the problem into smaller self-similar problems.  
- **Array Traversal**: Using `forEach()` to iterate.  
- **Spread Operator (`...`)**: Used to flatten arrays concisely.  
- **Array.isArray()**: A must-know method for checking if a value is an array.  
- **Depth Control in Recursion**: Managing depth in recursive algorithms.

---

# 🚀 **Support & Feedback**

✅ If you found this helpful, **please upvote & follow** for more clear JavaScript solutions!  
💬 Found a better approach or edge case? Let’s discuss and grow together! 🚀🔥

---
['JavaScript']