Monday, June 15, 2026
HomeLanguagesJavascriptHow to deep flatten an array in JavaScript?

How to deep flatten an array in JavaScript?

In this article, we will learn how to deep flatten an array in JavaScript. The flattening of an array is a process of merging a group of nested arrays present inside a given array. Deep flattening means that the array would be completely flattened.

Example:

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

This can be done using the following methods.

Method 1: Using the flat() method in JavaScript. This method merges all the nested arrays present inside an array. This method takes an argument depth, it is an Integer specifying how deep a nested array needs to be flattened. The depth value can be specified as infinity to completely flatten the array. The default value of this parameter is 1.

Example:

Javascript




<script>
  const arr = [1,2,3,4,5,[6,[7,8,9]]];
  
  // Setting the depth value to
  // Infinity to deep flatten the array
  const flattened = arr.flat(Infinity);
  console.log(flattened)
</script>


Output:

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

Method 2: Using the flatten() method of the Underscore library, the array can be flattened to any depth. It takes the array as an argument and returns the flattened array. The array is completely flattened if no depth parameter is passed to the method.

Example:

Javascript




const underscore = require('underscore');
const arr = [1,2,3,4,5,[6,[7,8,9]]];
  
// Using the flatten() method without
// depth parameter to deep flatten
// the array
const flattened_arr = underscore.flatten(arr);
console.log(flattened_arr);


Output:

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

Method 3: Using the flattenDeep() method of the Lodash library. This method is used to recursively flatten an array. It takes an array as an argument and returns the deep flattened array.

Example:

Javascript




const lodash = require('lodash');
const arr = [1,2,3,4,5,[6,[7,8,9]]];
  
// Using the flattenDeep() method
// to deep flatten the array
const flattened_arr = lodash.flattenDeep(arr);
console.log(flattened_arr);


Output:

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

Most Popular

Dominic
32516 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6897 POSTS0 COMMENTS
Nicole Veronica
12013 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6964 POSTS0 COMMENTS