Flatten an Array with Depth
Implement a function to flatten a multi-level nested array up to a specified depth. The function should accept two arguments: the array to be flattened (arr) and the depth of flattening (depth). This challenge should be tackled using both recursive and iterative approaches to offer different strategies for achieving the same outcome. Your version works like Array.prototype.flat(), which also takes a depth argument.
Recursive Solution:
The recursive approach involves a function that calls itself to flatten each level of nested arrays until the specified depth is reached. If the current item is an array and the depth has not been exceeded, the function recursively flattens this item and concatenates the result. If the item is not an array or the depth has been exceeded, it is added directly to the result. This approach elegantly handles nested arrays by leveraging the call stack, but it’s essential to manage the depth to avoid excessive recursion that can lead to a stack overflow.
Iterative Solution:
The iterative approach uses a stack to manage the array items. Each item from the input array is processed: if it’s an array and the depth allows, its items are added to the stack to be processed; otherwise, the item is added to the results. This method iteratively deconstructs the nested arrays without recursion, making it robust for deeply nested structures but potentially more complex to implement and understand.
Example Usage:
Consider an array [1, [2, [3, [4, 5]]], 6] with a depth of 2. The expected output would be [1, 2, 3, [4, 5], 6], flattening the array up to two levels deep but leaving any further nesting intact.
This problem tests your ability to manipulate arrays, handle recursion, and implement iterative solutions, all crucial skills for a frontend developer.
