Explorer
Node.js

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), []); } ```

Implement Array.prototype.myFlat

Medium
Implement `myFlat(arr, depth)` that flattens a nested array up to the given depth.
Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
[[1,2,[3,[4]]],[1,2,3,[4]],[1,2,3,4]]