js Easy
Intuition\n Describe your first thoughts on how to solve this problem. \nThe function utilizes a recursive approach to reduce the depth of the nested array laye
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe function utilizes a recursive approach to reduce the depth of the nested array layer by layer. For each recursive call, the function decreases the allowed depth by 1 until it reaches 0, at which point the array is no longer flattened further.\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nBase Case:\nIf n (the remaining depth) is less than 1, the function returns a shallow copy of the array using slice(). This ensures no further flattening is done.\n\nRecursive Case:\nUse Array.prototype.reduce to iterate through the array.\n\nIf the current element (val) is an array, recursively flatten it with the depth decreased by 1.\nIf it\u2019s not an array, append it directly to the accumulator.\nCombining Results:\nFor each element, either push the flattened result of the nested array or the element itself to the accumulator. This builds the flattened array up to the specified depth.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n(n)\n\n# Code\n```javascript []\n/**\n * @param {Array} arr\n * @param {number} depth\n * @return {Array}\n */\nvar flat = function (arr, n) {\n    \n    if(n < 1){\n        return arr.slice()\n    }\n\n    return arr.reduce((acc,val)=>{\n        if(Array.isArray(val)){\n            acc.push(...flat(val,n-1))\n        } else {\n            acc.push(val)\n        }\n\n        return acc\n    },[])\n\n};\n```
['JavaScript']