Implement `myFlat(arr, depth)` that flattens a nested array up to the given depth.
Problem Statement
Implement `myFlat(arr, depth)` that flattens a nested array up to the given depth.
Complexity
Time Complexity: -
Space Complexity: -
Hints
š” Hint 1:
Recursively flatten if depth > 0.
š” Hint 2:
Check if each element is an array. If so, recurse with depth - 1.
š” Hint 3:
Use reduce and concat: arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? myFlat(val, depth-1) : val), []).
ā
Solution:
```javascript
function myFlat(arr, depth = 1) {
if (depth <= 0) return arr.slice();
return arr.reduce((acc, val) =>
acc.concat(Array.isArray(val) ? myFlat(val, depth - 1) : val), []);
}
```