Solution Walkthrough
IntuitionWe need a recursive function that can flatten the array based on n. For this, the function needs to know how deeply nested it is.Approach
We begin with
# Intuition
We need a recursive function that can flatten the array based on `n`. For this, the function needs to know how deeply nested it is.  

# Approach

1. We begin with a simple copy of `arr`:
```javascript []
var flat = function (arr, n) {
    let res = [];
    for (const item of arr) res.push(item);
    return res
};

```

This function returns a new array `res` that has every item in `arr`. 

2. Next we can write the bones of the recursive function. Our function should take an `element`, check if it's an array. the function should call itself for every `item` in that `element`. If it's not an array, push to `res`.

```javascript []
var flat = function (arr, n) {
    let res = [];

    function recurse(element, depth) {
        if (Array.isArray(element)) {
            for (const item of element) {
                recurse(item, 0);
            }
        } else {
            res.push(element);
        }
    }
    
    for (const item of arr) {
        recurse(item, 0)
    }

    return res
};
```

`depth` here has no current use; it's just a place marker. The function at this point flattens `arr` without discretion. What we need now is to count decisively! 

We can add `depth += 1` before running the `for...loop` inside `recurse()`, this way every `item` in the `element` begins with the same `depth`. We also need to reset the `depth` if we are pushing to `res`, so `depth = 0` should go just before that.


# Code
```javascript []
/**
 * @param {Array} arr
 * @param {number} depth
 * @return {Array}
 */
var flat = function (arr, n) {
    let res = [];

    function recurse(element, depth) {
        if (Array.isArray(element) && depth < n) {
            depth += 1;
            for (const item of element) {
                recurse(item, depth)
            }
        } else {
            depth = 0
            res.push(element)
        }
    }

    for (const item of arr) {
        recurse(item, 0)
    }

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