Flatten a Nested Array With a Generator

GeneratorsIteratorsArrays

Write a generator function flattenNested(arr) that walks an array nested to any depth and yields its numbers one by one, left to right.

Because it is a generator, the caller can take values one at a time and stop early — nothing is materialised up front.

Examples

Example 1
Input
[...flattenNested([1, [2, 3], [[4]]])];
Output
[1, 2, 3, 4]
Explanation
Spreading drains the generator, but next() one value at a time works just as well.

Constraints

  • Every item is either a number or another array
  • Any array, at any level, may be empty

Notes

  • `yield*` delegates to a recursive call and forwards every value from it.
  • Calling a generator function runs none of its body — the first `next()` does.

Hints

Read the full write-up for Flatten a Nested Array With a Generator
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it