JavaScript Intermediate

Implement array flattening (flatten)

AI Practice

What is Array Flattening?

Converting a nested array into a single-level array.

// Input
[1, [2, [3, [4]], 5]]

// Output (fully flattened)
[1, 2, 3, 4, 5]

Method 1: Array.prototype.flat() (ES2019)

[1, [2, [3]]].flat();         // [1, 2, [3]] (default depth: 1)
[1, [2, [3]]].flat(2);        // [1, 2, 3]
[1, [2, [3]]].flat(Infinity); // [1, 2, 3] (fully flattened)

Method 2: Recursive Implementation

function flatten(arr) {
  return arr.reduce((result, item) => {
    if (Array.isArray(item)) {
      return result.concat(flatten(item));
    }
    return result.concat(item);
  }, []);
}

flatten([1, [2, [3, [4]], 5]]); // [1, 2, 3, 4, 5]

Method 3: Flatten with Depth

function flattenDepth(arr, depth = 1) {
  if (depth === 0) return arr.slice();
  return arr.reduce((result, item) => {
    if (Array.isArray(item) && depth > 0) {
      return result.concat(flattenDepth(item, depth - 1));
    }
    return result.concat(item);
  }, []);
}

flattenDepth([1, [2, [3, [4]]]], 2); // [1, 2, 3, [4]]

Method 4: Iterative with Stack (non-recursive, better performance)

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

Method 5: flatMap (flatten + map in one step)

// Only flattens one level, but combines well with map
[1, 2, 3].flatMap(x => [x, x * 2]); // [1, 2, 2, 4, 3, 6]

✦ AI Mock Interview

Type your answer and get instant AI feedback

Sign in to use AI scoring

Copyright © 2026 Wood All Rights Reserved · FE Interview Hub