JavaScript Quirks

Flatten Array

mediumjs-quirksrecursionarray
0:00

Problem

Implement `flatten(arr)` that recursively flattens a nested array of any depth into a single-level array. Do not use `Array.prototype.flat(Infinity)`.

Your solution
Test results
Click Run tests to check your solution against the test cases.

About this challenge

Flatten Array is a medium javascript quirks coding challenge. It explores a surprising corner of JavaScript's behavior — the kind of gotcha that causes real bugs. Write your solution in the editor above, run it against the test cases, and get instant feedback — free, in your browser, no sign-up.

Show a hint & approach (spoiler)

Hint: Use reduce: for each element, concat flatten(el) if it is an array, else concat el.

Keep practicing

Browse all coding challenges, or build intuition for the underlying concepts with the algorithm visualizers and the developer cheatsheets.