A warm-up question that checks whether you reach for recursion cleanly and remember that flat() takes a depth.
reduce builds a new array; for each element decide: is it a nested array with depth remaining? Recurse. Otherwise keep it.
arr.flat(Infinity)?" → that's the real-world answer; the interviewer wants the algorithm behind it.Write the recursive version, then the stack-based one, and be ready to say which you'd ship and why.
function flatten(arr, depth = Infinity) { // your code here } console.log(flatten([1, [2, [3, [4]]]])); // [1, 2, 3, 4] console.log(flatten([1, [2, [3, [4]]]], 1)); // [1, 2, [3, [4]]]
Test Code
Enter JavaScript that runs after your solution. It should return a value or a Promise.