Open In App
Related Articles

How to deep flatten an array in JavaScript?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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]


Last Updated : 01 Apr, 2021
Like Article
Save Article
Share your thoughts in the comments
Similar Reads