#Generators#Iterators

Nested Array Generator

Yield every value in a nested array one at a time, so an enormous structure is never flattened into memory.

By Pratik RaiMedium

Write a generator function inorderTraversal(arr) that yields every integer in a multidimensional array, in order.

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

Examples

Input:

JSfile.javascript
1[...inorderTraversal([1, [2, 3], [[4]]])];

Output:

[1, 2, 3, 4]

Spreading drains the generator, but next() one value at a time works just as well.

Constraints

  • 0 <= number of integers <= 10^5
  • Nesting may be arbitrarily deep

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.

Goal: Yield each value lazily, delegating into nested arrays.

Source

Frequently asked questions

What is a generator function in JavaScript?
A function declared with `function*` that can pause at each `yield` and resume where it left off. Calling it returns an iterator rather than running the body.
Why use a generator instead of returning an array?
Because values are produced on demand. A caller that only needs the first few never pays for the rest, and an enormous or infinite structure never has to exist in memory at once.
What does yield* do?
It delegates to another iterable and forwards every value it produces. For a recursive traversal it replaces a manual loop over the inner generator with a single line.
When does the body of a generator actually run?
Not when you call it — that only creates the iterator. The body starts on the first `next()` and pauses again at each `yield`, which is exactly what makes it lazy.

Related Challenges

Continue learning with these related challenges

View All
JavaScript

Array.prototype.groupBy

Group an array into buckets by a key function — now a real language feature as Object.groupBy.

JavaScript · ES6Pratik Rai ·

JavaScript

Flatten an Array Without Recursion

The same result as the recursive flatten, with your own stack instead of the call stack.

JavaScript · ES6Pratik Rai ·

JavaScript

Flatten Nested Array in JavaScript

Implement a function to flatten a nested array in JavaScript.

JavaScript · Arrays · RecursionPratik Rai ·