A nested array — an array that contains other arrays inside it, possibly several levels deep — needs to be “flattened” into a single flat array for a lot of real tasks, like merging paginated results or normalizing tree-like data. JavaScript has both a built-in method and a manual recursive solution for this.

JavaScript Program to Flatten a Nested Array (Using flat())

const nested = [1, [2, 3], [4, [5, 6, [7, 8]]], 9];

const flatArray = nested.flat(Infinity);

console.log(flatArray);

Output:

[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]


JavaScript Program to Flatten a Nested Array (Using Recursion)

flat(Infinity) is supported in every modern browser and Node.js version, but understanding the recursive approach behind it is useful for interviews and for older environments that don’t support it.

function flattenArray(arr) {
  let result = [];

  for (const item of arr) {
    if (Array.isArray(item)) {
      result = result.concat(flattenArray(item)); // recurse into nested arrays
    } else {
      result.push(item);
    }
  }

  return result;
}

console.log(flattenArray([1, [2, 3], [4, [5, 6, [7, 8]]], 9]));

Output:

[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

The recursive version calls itself on any array it finds inside the current array, so it correctly handles any depth of nesting — not just two or three levels. Both approaches run in O(n) relative to the total number of elements across all nested levels.