JavaScript | Flatten Deeply Nested Array
Intuition\n Describe your first thoughts on how to solve this problem. \nPre-defined terms:\n\n1. Multi-dimensional array \u2192 a recursive data structure that
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nPre-defined terms:\n\n1. `Multi-dimensional array` \u2192 a recursive data structure that contains integers or other multi-dimensional arrays\n\n2. `Flattened array` \u2192 a version of that array with some or all of the sub-arrays removed and replaced with the actual elements in that sub-array\n\nWe need to return a flattened version of the given multi-dimensional array.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. These are comment delimiters for a multi-line comment to help explain and document code while preventing ignored text from executing. These comments are commonly used in formal documentation for better code understanding.\n\n    ```\n    /**\n    * Multi-line comment\n    */\n    ```\n\n2. This is a special type of comment called a JSDoc comment that explains that the function should take parameters named `arr` and `depth`, which are expected to be an `Array` and a `number`.\n\n    ```\n    @param {Array} arr\n    @param {number} depth\n    ```\n\n3. This is a special type of comment called a JSDoc comment that explains what the code should return, which, in this case, is an `Array`. It helps developers and tools like code editors and documentation generators know what the function is supposed to produce.\n\n    ```\n    @return {Array}\n    ```\n\n4. This is how we define a function named `flat` that takes an array `arr` and a number `n` as its arguments.\n\n    ```\n    var flat = function (arr, n) {\n        // code to be executed\n    };\n    ```\n\n5. This `flat` method flattens the array `arr` up to depth `n`.\n\n    ```\n    return arr.flat(n)\n    ```\n\n# Complexity\n- Time complexity: $O(n)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n`n` is the total number of elements in the input array. This is because the code needs to iterate over each element in the array.\n\n- Space complexity: $O(n)$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n`n` is the total number of elements in the input array. This is because the function creates a new array with all the elements from the sub-arrays, so the space required is proportional to the number of elements in the input array.\n\n# Code\n```\n/**\n * @param {Array} arr\n * @param {number} depth\n * @return {Array}\n */\nvar flat = function (arr, n) {\n    return arr.flat(n)\n};\n```
['JavaScript']