Back to More
Challenge of the Week

Flatten a Nested Array

Solve it. Learn something. Move on.

The Challenge

Write a function that takes a nested array and returns a flat array with all values in order. Handle any depth of nesting.

Input:  [1, [2, [3, [4, 5]]], 6]
Output: [1, 2, 3, 4, 5, 6]

Input:  [[1, 2], [3, [4, [5]]]]
Output: [1, 2, 3, 4, 5]

Rules

  • Do not use Array.prototype.flat() — that would be cheating.
  • Do not use Lodash or any external library.
  • Bonus: Solve it with recursion AND with a stack.

💡 Solution

Recursive Approach

function flatten(arr) {
  let result = [];
  for (const item of arr) {
    if (Array.isArray(item)) {
      result.push(...flatten(item));
    } else {
      result.push(item);
    }
  }
  return result;
}

Iterative (Stack) Approach

function flatten(arr) {
  const stack = [...arr];
  const result = [];
  while (stack.length) {
    const item = stack.shift();
    if (Array.isArray(item)) {
      stack.unshift(...item);
    } else {
      result.push(item);
    }
  }
  return result;
}

What You Learned

  • Recursion

    A function that calls itself — elegant but risks stack overflow for very deep nesting.

  • Stack data structure

    An iterative approach avoids recursion limits and is often faster.

  • Array.isArray()

    Always check if a value is an array before treating it as one.