Flatten a Nested Array With a Generator
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
[...flattenNested([1, [2, 3], [[4]]])];[1, 2, 3, 4]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
Editorial: Flatten a Nested Array With a Generator
Yielding instead of returning
A function that returns an array has to build the whole array first. A generator hands back one value at a time, so a caller who wanted the first three can stop after three.
Approach
yield* delegates to a recursive call and forwards every value it produces.
Implementation
function* flattenNested(arr) { for (const item of arr) { if (Array.isArray(item)) yield* flattenNested(item); else yield item; } }
Worth knowing
Calling a generator function runs none of its body — it returns an iterator, and the first next() starts execution. That laziness is the entire reason to reach for one.
yield* is doing real work here: without it you would loop over the inner generator and yield each value manually. With it, the delegation is one line and the recursion reads like the non-generator version.