How to deep flatten an array in JavaScript? (original) (raw)
Last Updated : 01 Apr, 2021
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]]];
`` 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]]];
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. Thismethod 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]]];
const flattened_arr = lodash.flattenDeep(arr);
console.log(flattened_arr);
Output:
[1,2,3,4,5,6,7,8,9]