Array.prototype.groupBy
Group an array into buckets by a key function — now a real language feature as Object.groupBy.
JavaScript · ES6 — Pratik Rai ·
Yield every value in a nested array one at a time, so an enormous structure is never flattened into memory.
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.
Input:
JSfile.javascript1[...flattenNested([1, [2, 3], [[4]]])];
Output:
[1, 2, 3, 4]
Spreading drains the generator, but next() one value at a time works just as well.
yield* delegates to a recursive call and forwards every value from it.next() does.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.
yield* delegates to a recursive call and forwards every value it produces.
JSfile.javascript1function* flattenNested(arr) { 2 for (const item of arr) { 3 if (Array.isArray(item)) yield* flattenNested(item); 4 else yield item; 5 } 6}
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.
Goal: Yield each value lazily, delegating into nested arrays.
function* that can pause at each yield and resume where it left off. Calling it returns an iterator rather than running the body.next() and pauses again at each yield, which is exactly what makes it lazy.Continue learning with these related challenges
Group an array into buckets by a key function — now a real language feature as Object.groupBy.
JavaScript · ES6 — Pratik Rai ·
The same result as the recursive flatten, with your own stack instead of the call stack.
JavaScript · ES6 — Pratik Rai ·
Implement a function to flatten a nested array in JavaScript.
JavaScript · Arrays · Recursion — Pratik Rai ·
Group an array into buckets by a key function — now a real language feature as Object.groupBy.
JavaScript · ES6
Pratik Rai ·
The same result as the recursive flatten, with your own stack instead of the call stack.
JavaScript · ES6
Pratik Rai ·
Implement a function to flatten a nested array in JavaScript.
JavaScript · Arrays · Recursion
Pratik Rai ·