Skip to curriculum
Jump to the editor

21.1. Flatten an array to any depth, recursively and with a stack

Easy
Topics
15–25 min

Nested 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

JAVASCRIPT
function flattenDeep(array, depth = Infinity)      // returns a new array
function flattenDeepStack(array, depth = Infinity) // returns a new array
  • array: 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.

  1. With no depth, every level of nesting is removed, and the items keep their order.
  2. The result is a new array, even when nothing was nested.
  3. depth 1 removes one level, depth 2 two levels. An inner array below the depth stays in the result as the same array object.
  4. depth 0 or a negative depth returns a shallow copy: a new outer array holding the same items.
  5. Empty inner arrays add nothing.
  6. Holes (indexes an array does not have) are skipped, as flat skips them. Items that are really undefined or null are kept.
  7. Only real arrays are taken apart (Array.isArray): strings, Sets, plain objects and objects with a length stay as single items.
  8. The input arrays are not changed.
  9. Array.prototype.flat and flatMap are not used.
  10. An array used twice (but not inside itself) is flattened each time it appears.
  11. At depth Infinity, an array that contains itself, directly or deeper, makes the function throw a TypeError instead of running forever. With a finite depth there is no error: the cycle is followed that many levels, as flat does.
  12. flattenDeep handles 1,000 levels. flattenDeepStack handles 100,000 levels.

Examples

JAVASCRIPT
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)
JAVASCRIPT
const loop = [1];
loop.push(loop);
flattenDeep(loop, 2);  // [1, 1, 1, loop]
flattenDeep(loop);     // throws TypeError
JAVASCRIPT
let 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 allowed

Environment

  • Plain JavaScript in a browser page; the tests call the globals flattenDeep and flattenDeepStack from flatten.js.
  • Array.prototype.flat and flatMap are removed during one test. push, pop and the other array methods are fine.
  • flattenDeepStack must not call itself or any other function once per level.

Hints

  1. In the recursive version, what does one call need to know besides the array: how many levels are still allowed?
  2. 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?
  3. 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
Back to the question
Loading the editor…