100% Simple and Easy explanation | Faster Recursive Solution
Understanding the Problem Statement\n\nWe have given a multi-dimensional array, let\'s suppose,\n\narr = [[1, 2], [3, [4, 5]]].\n\nThis array has two elements, 
**Understanding the Problem Statement**\n\nWe have given a multi-dimensional array, let\'s suppose,\n\n`arr = [[1, 2], [3, [4, 5]]]`.\n\nThis array has two elements, each of which is itself an array. The first element **[1, 2]** has a depth of **1**, while the second element **[3, [4, 5]]** has a depth of **2**.\n\nTo flatten this array means to create a new array that contains all the elements of the original array, but with the nested arrays **"flattened out"** so that they no longer exist. For example, if we flatten arr with a depth of **1**, we would get:\n\n`answer = [1, 2, 3, [4, 5]];`\n\nThe sub-array **[4, 5]** was not flattened, since its depth is greater than the specified depth of 1.\n\n\n**Intuition**\n\nWe can divide the problem into **sub-problems** as nested list can have any depth levels. Since we have to check for all the levels and flatten the array if depth is greater than 0, we can use **recursion** to do this.\n\n**Approach**\n\n1. Check if **n is equal to 0**, Simply return the original array as no flattening is required.\n2. Initialize an `answer` array to store the result.\n3. Now, traverse the array using for loop, and for each array check if n is greater than zero and element is instance of the `Array` : \n\t* \tIf both the conditions are true, recursively call the function by passing `arr[i]` and reducing the n by 1 and add the result to answer array using the spread `...` operator.\n\t* \tElse, Push the current array `arr[i]` to the `answer` array.\n4. Return the `answer` array once the traversal is complete.\n\n\n**Code**\n```\nvar flat = function (arr, n) {\n    \n    // if n is 0, no flattening is required, hence return the original array\n    if(n == 0){\n        return arr;\n    }\n    \n    // create an answer array to store final result\n    let answer = [];\n    \n    // traverse the array\n    for(let i=0; i<arr.length; i++){\n        \n        // check if element is instance of array and depth is not equal to 0\n        if(n>0 && Array.isArray(arr[i])){\n            \n            // recursively call the function for this array and push the flattened array to the answer array\n            answer.push(...flat(arr[i], n-1));\n        }\n        // else directy push the current array\n        else{\n            answer.push(arr[i]);\n        }\n    }\n    \n    return answer;\n};\n```\n\n**Output**\n![image](https://assets.leetcode.com/users/images/b3d8e1e7-3b1f-4ce0-a7bc-716f2a8143b6_1681454902.9784133.png)\n
['Recursion', 'JavaScript']