Explained with help of an example
Example Walkthrough:\n- For input arr = [1, [2, [3, 4], 5], 6] and n = 2, here\u2019s what happens step-by-step:\n    - The helper function starts with the oute
# Example Walkthrough:\n- For input arr = [1, [2, [3, 4], 5], 6] and n = 2, here\u2019s what happens step-by-step:\n    - The helper function starts with the outer array [1, [2, [3, 4], 5], 6] and depth 0.\n        - It adds 1 to res.\n        - It sees the sub-array [2, [3, 4], 5] and recursively calls helper with this sub-array and depth 1.\n            - It adds 2 to res.\n            - It sees the nested array [3, 4] and calls helper recursively with depth 2.\n                - It adds 3 and 4 to res.\n            - It adds 5 to res.\n        - It adds 6 to res.\n    - The function returns [1, 2, 3, 4, 5, 6].\n\n# Code\n```typescript []\ntype MultiDimensionalArray = (number | MultiDimensionalArray)[];\n\nvar flat = function (arr:  MultiDimensionalArray, n: number):  MultiDimensionalArray {\n    const res:MultiDimensionalArray = [];\n\n    function helper(arr:MultiDimensionalArray, depth: number): MultiDimensionalArray{\n        for(const val of arr){\n            if(typeof val === \'object\' && depth < n){\n                helper(val,depth + 1);\n            }\n            else res.push(val);\n        }\n        return res;\n    }\n\n    return helper(arr,0);\n\n};\n```
['TypeScript']