DEV Community

Hiral
Hiral

Posted on

Array Flatten in JavaScript

What is a Nested Array?

A nested array is simply an array that contains other arrays inside it.
This nesting can go to any depth (even infinitely).

[5, 6, [7, 8]]
[5, 6, [7, 8, [8, 9]]]
Enter fullscreen mode Exit fullscreen mode

Why Do We Need to Flatten Arrays?

Working with deeply nested arrays in real-world applications can be difficult.
To make data easier to process, we flatten the array—i.e., convert it into a single-level array.

[5, 6, [7, 8]]            → [5, 6, 7, 8]
[5, 6, [7, 8, [8, 9]]]    → [5, 6, 7, 8, 8, 9]
Enter fullscreen mode Exit fullscreen mode

Methods to Flatten an Array

  1. Using Built-in flat() Method JavaScript provides a built-in method called flat().
let arr = [1, 2, [3, 4], [7, 8, [9, 10]]];
console.log(arr.flat(Infinity));
// Output: [1, 2, 3, 4, 7, 8, 9, 10]
Enter fullscreen mode Exit fullscreen mode
  • flat() takes a depth level as an argument.
  • Infinity ensures the array is flattened completely.

Example with limited depth:

let arr1 = [1, 2, [3, 4], [7, 8, [9, 10, [5, 6]]]];
console.log(arr1.flat(2));
// Output: [1, 2, 3, 4, 7, 8, 9, 10, [5, 6]]
Enter fullscreen mode Exit fullscreen mode
  1. Using Recursion

This method manually traverses each element and flattens nested arrays.

const array = [[5, 6, [4, 5]], [7, 8], 9, 10];
let result = [];

function flattenArray(arr) {
  for (let i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      flattenArray(arr[i]); // recursive call
    } else {
      result.push(arr[i]);
    }
  }
}

flattenArray(array);
console.log(result);
// Output: [5, 6, 4, 5, 7, 8, 9, 10]
Enter fullscreen mode Exit fullscreen mode
  1. Using Stack (Iterative Approach) This avoids recursion by using a stack.
let arr1 = [1, 2, [3, 4], [7, 8, [9, 10, [5, 6]]]];
let stack = [...arr1];
let result = [];

while (stack.length) {
  let item = stack.pop();

  if (Array.isArray(item)) {
    stack.push(...item);
  } else {
    result.push(item);
  }
}

console.log(result.reverse());
// Output: [1, 2, 3, 4, 7, 8, 9, 10, 5, 6]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)