Recursive TypeScript solution
Approach\nAny time I need to traverse a nested data structure, I reach for recursion.\n\nIntuitively, we need to loop through the array and check if each elemen
# Approach\nAny time I need to traverse a nested data structure, I reach for recursion.\n\nIntuitively, we need to loop through the array and check if each element is a number. If so, it is already flat, so it can be pushed into our result. If the element is also an array, we need to loop it as well and check each of its elements, etc., until we reach the level requested.\n\nSo we need to create a function that will check each element in an array and recursively flatten it if it is also an array.\n\n# Complexity\n- Time complexity: $$O(n)$$ because in the worst case, we have to check every element of the array.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$ because we are using recursion, which means we will be pushing function calls onto the stack. In the worst case, we push a function call for each element of each array.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\ntype MultiDimensionalArray = (number | MultiDimensionalArray)[];\n\n\nvar flat = function (arr:  MultiDimensionalArray, n: number):  MultiDimensionalArray {\n\n    // base case. If we are on depth 0, we don\'t flatten the element\n    if (n === 0) {\n        return arr;\n    }\n    \n    // temp array to hold the flattened results for this level of the recursion\n    const result: MultiDimensionalArray = [];\n\n    // loop the elements of this array. If they are numbers, don\'t need to flatten,\n    // just push into the result. If they are arrays, we need to flatten,\n    // so recursively call the flat function, then spread the returned value and push into result.\n    arr.forEach(el => {\n        if (typeof el === \'number\') {\n            result.push(el);\n        } else {\n            result.push(...flat(el, n - 1));\n        }\n    })\n\n    return result;\n};\n\n\n\n```
['TypeScript']