← Daily Logs
GreatFrontEnd

Flatten an Array

EasyJul 1, 2026arrayrecursion

Collapse an arbitrarily nested array into a single level — the textbook recursion warm-up, and a reminder that production code should just reach for the built-in `Array.prototype.flat(Infinity)`.

The problem

Write a function `flatten` that returns a new array with every subarray element concatenated recursively into a single level. Single-level arrays come back unchanged; nesting of any depth is fully unwrapped.

So `flatten([1, [2, [3, [4]]]])` becomes `[1, 2, 3, 4]`. The interesting part is that the depth is unknown, so the solution has to keep descending until there's nothing left to unwrap.

The approach

Walk the input once and branch on each element: if it's an array, recurse and spread the flattened result into the accumulator; otherwise push the value straight through. `Array.isArray` is the check that decides which path an element takes.

The recursion carries the depth for me — each nested array spawns its own `flatten` call, so a value buried four levels deep just rides four stacked returns back up to the top-level `result`. The base case is implicit: an array with no sub-arrays never recurses and simply copies its values across.

Worth naming the real-world footnote: in actual code this is a one-liner — `arr.flat(Infinity)`. You only hand-roll it when you need to keep certain values intact (typed arrays, Buffers), flatten trees of objects rather than arrays, or go iterative to dodge recursion limits on adversarially deep input.

The solution

js
/**
 * @param {Array<*|Array>} value
 * @return {Array}
 */
export default function flatten(value) {

  const result = []
  for(let i of value) {
    if(Array.isArray(i)) {
      result.push(...flatten(i))
    } else {
      result.push(i)
    }
  }
  return result
}

Time O(n)Space O(n)

All entries