Write a function flatten(arr, depth) that flattens a nested array up to the specified depth (defaulting to 1). For example, flatten([1, [2, [3, [4]]]], 2) should return [1, 2, 3, [4]].
function flatten(arr, depth = 1) {
// Your code here
}
Rules:
- Do not use the built-in Array.prototype.flat() method.
- Must support a custom depth parameter that defaults to 1.
- Return a new array without mutating the original input.
Post your solution as a reply. Answer goes up in about a day.