Skip to main content

Command Palette

Search for a command to run...

Array Flatten in JavaScript

Updated
4 min readView as Markdown
Array Flatten in JavaScript
V
Blog on different tools and technology or concept that useful for the begineer that start their jouney in software industry

In this javascript tutorial blog we are going to discuss about nested array related stuff and how to handle these array, and even why we need to handle so i hope this blog will going to helpful for you, so let's begin with simple question ?

What is Nested array ?

An array is a collection of elements, and those elements can be of any type such as numbers, strings, booleans, objects, or even other arrays.

When an array contains another array as one of its elements, it is called a nested array.

Example

let arr1 = [ , , , ] // simple array

let arr2 = [ [], [], []] // 1 level nested array

let arr3 = [ [ [], [] ], [ [], [] ], [ [], [] ] ] // 2 level nested array

let arr4 = [ [ [ [ [], [] ], [ [], [] ] ], [ [ [] ] ] ], [ [ [ [], [] ], [ [] ] ], [ [ [] ] ] ] ] // 3 level nested array 

If you confuse after seen too many nesting at anywhere see step by step and level wise.


What does the meaning of flatten array ?

Flattening means converting a nested array into a single-level (simple) array that contains all the values.

Example

let arr1 = [ [ [ [ [ 1 ], [ 2 ] ], [ [ 3 ], [ 4 ] ] ], [ [ [ 5 ] ] ] ], [ [ [ [ 6 ], [ 7 ] ], [ [ 8 ] ] ], [ [ [ 9 ] ] ] ] ]
// this is 3-level nested array

// convert in into simple array
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]

Now we move to most important part of blog is approach to convert into flatten array.


Different approach to convert into flatten array

Recusive approach

In this classical approach we use recusion like if current element is still array flat it upto not non array element.

let arr = [ [ [ [ [ 1 ], [ 2 ] ], [ [ 3 ], [ 4 ] ] ], [ [ [ 5 ] ] ] ], [ [ [ [ 6 ], [ 7 ] ], [ [ 8 ] ] ], [ [ [ 9 ] ] ] ], 10]

function flatten(arr) { 
   let res = []
   
for(let item of arr) {

 // still array 
  if(Array.isArray(item)){
    
// call again flatten with new arr
    res = res.concat(flatten(item));
  }
else // simple element 
   res.push(item)

}
 return res;
}

console.log(flatten(arr)) 
// Array [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Built-in Method: .flat()

Javascript also provide built-in methode to convert nested array into flatten array with constraints upto certain level.

const arr = [1, [2, [3, [4]]]];

arr.flat(1);        // [1, 2, [3, [4]]]
arr.flat(2);        // [1, 2, 3, [4]]
arr.flat(Infinity); // [1, 2, 3, 4] 

reduce() + Recursion

We can also use reduce() methode along with recursion for convert into flatten array.

const arr = [1, [2, [3, [4], 5], 6], 9];

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

console.log(flatten(arr));
// Array [1, 2, 3, 4, 5, 6, 9]

Iterative Approach (Stack-Based)

In this appraoch we use stack instead of recusion call and convert.

function flatten(arr) {
  
// inti stack
  const stack = [...arr];
  const result = [];

// not stack not empty
  while (stack.length) {
    const current = stack.pop();
    
// still array , push new element into stack
    if (Array.isArray(current)) 
      stack.push(...current);
     else  // push into result
      result.push(current);
  }
  // reverse result
  return result.reverse();
}


const arr = [1, [2, [3, [4], 5], 6], 9, 10];
console.log(flatten(arr));
// Array [1, 2, 3, 4, 5, 6, 9, 10]

Conclusion

Flattening nested arrays simplifies data access and lets you apply array operations more easily. Prefer Array.prototype.flat (or flatMap) when available; use .flat(Infinity) only if you truly need to collapse all depths. For older environments or extremely deep nesting, use an iterative (stack-based) or controlled-recursion approach to avoid stack overflows.