21.1. Flatten an array to any depth, recursively and with a stack
Topics
This question is in
21. Recursion and nested dataNested arrays turn up whenever data is built in pieces: a list of pages where each page holds a list of rows, a menu whose groups hold more groups, the results of several requests collected together. Before you can count, search or render the items, you often need one flat list.
Write the same flattening twice in flatten.js. flattenDeep uses recursion: a function that reads an array and calls itself for each inner array. flattenDeepStack gives the same results with a loop and an explicit stack, so input nested 100,000 levels deep does not overflow the call stack.
Signature
function flattenDeep(array, depth = Infinity) // returns a new array
function flattenDeepStack(array, depth = Infinity) // returns a new arrayarray: the array to flatten. It is never changed.depth: how many levels of nesting to remove. When it is missing, every level is removed.- Both return a new array with the items in their original order.
Requirements
Both functions must follow every rule, unless a rule names one of them.
- With no
depth, every level of nesting is removed, and the items keep their order. - The result is a new array, even when nothing was nested.
depth1 removes one level,depth2 two levels. An inner array below the depth stays in the result as the same array object.depth0 or a negative depth returns a shallow copy: a new outer array holding the same items.- Empty inner arrays add nothing.
- Holes (indexes an array does not have) are skipped, as
flatskips them. Items that are reallyundefinedornullare kept. - Only real arrays are taken apart (
Array.isArray): strings, Sets, plain objects and objects with alengthstay as single items. - The input arrays are not changed.
Array.prototype.flatandflatMapare not used.- An array used twice (but not inside itself) is flattened each time it appears.
- At depth
Infinity, an array that contains itself, directly or deeper, makes the function throw aTypeErrorinstead of running forever. With a finite depth there is no error: the cycle is followed that many levels, asflatdoes. flattenDeephandles 1,000 levels.flattenDeepStackhandles 100,000 levels.
Examples
flattenDeep([1, [2, [3, [4]]]]); // [1, 2, 3, 4]
flattenDeep([1, [2, [3, [4]]]], 1); // [1, 2, [3, [4]]]
flattenDeepStack([[], [1, , 2], "ab"]); // [1, 2, "ab"] (the hole is skipped)const loop = [1];
loop.push(loop);
flattenDeep(loop, 2); // [1, 1, 1, loop]
flattenDeep(loop); // throws TypeErrorlet deep = [0];
for (let i = 0; i < 100000; i += 1) deep = [deep];
flattenDeepStack(deep); // [0]
flattenDeep(deep); // may throw RangeError: the call stack is too small, and that is allowedEnvironment
- Plain JavaScript in a browser page; the tests call the globals
flattenDeepandflattenDeepStackfromflatten.js. Array.prototype.flatandflatMapare removed during one test.push,popand the other array methods are fine.flattenDeepStackmust not call itself or any other function once per level.
Hints
- In the recursive version, what does one call need to know besides the array: how many levels are still allowed?
- A stack that holds whole arrays loses your place in the outer array. What else does each entry need to remember so the items come out in order?
- Which arrays count for a cycle: every array seen so far, or only the ones you are still inside of?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it