Docs

JS Machine Coding Questions — Implementations You Must Know

Flatten — nested array (5.1)


  • Flatten [1, [2, [3]]] → [1, 2, 3]. Only arrays, no object key paths.
  • Recursive: reduce with optional depth param. Built-in: arr.flat(Infinity).
  • Iterative (stack): avoids deep recursion stack overflow.
  • Gotcha: Iterative unshift is O(n) per step — for huge inputs, push and reverse() at the end instead.
1// Recursive with depth 2function flatten(arr, depth = Infinity) { 3 return arr.reduce((acc, item) => { 4 if (Array.isArray(item) && depth > 0) { 5 acc.push(...flatten(item, depth - 1)); 6 } else { 7 acc.push(item); 8 } 9 return acc; 10 }, []); 11} 12 13// Iterative (stack) 14function flattenIterative(arr) { 15 const stack = [...arr]; 16 const result = []; 17 while (stack.length) { 18 const item = stack.pop(); 19 if (Array.isArray(item)) stack.push(...item); 20 else result.unshift(item); 21 } 22 return result; 23}