Recursively flatten a nested array of any depth in JavaScript
This post will discuss how to recursively flatten a nested array of any depth in JavaScript.
There are several methods to flatten an array of any depth. These are discussed below in detail:
1. Using Array.prototype.concat() function
This can be recursively done using the reduce() method with the concat() method. The following example demonstrates how to recursively deep flatten array with reduce and concat method.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
function flatten(arr) { return arr.reduce((acc, cur) => acc.concat(Array.isArray(cur) ? flatten(cur) : cur), []); }; const arr = [[1,2],[3,[4,[5]]]]; const flattened = flatten(arr); console.log(flattened); /* Output: [ 1, 2, 3, 4, 5 ] */ |
2. Using Array.prototype.flat() function
ECMA 2019 introduced a new method called flat() for recursively flatten an array. It takes the depth of the nested array as a parameter, which is 1 by default. To flatten any depth of a nested array, use the Infinity with the flat() method.
|
1 2 3 4 5 6 7 8 |
const arr = [[1,2],[3,[4,[5]]]]; const flattened = arr.flat(Infinity); console.log(flattened); /* Output: [ 1, 2, 3, 4, 5 ] */ |
3. Using generator function
Alternatively, you can write a generator function for deep flatten an array of any depth. The following code example shows how to implement this using the Array.isArray() method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
function* flatten(arr) { for (const val of arr) { Array.isArray(val) ? yield* flatten(val) : yield val; } } const arr = [[1,2],[3,[4,[5]]]]; const flattened = [...flatten(arr)]; console.log(flattened); /* Output: [ 1, 2, 3, 4, 5 ] */ |
4. Using Underscore Library
Underscore JavaScript library offers the _.flatten method, which can flatten a nested array of any depth.
|
1 2 3 4 5 6 7 8 9 10 |
const _ = require('underscore'); const arr = [[1,2], [3,[4,5]]]; const flattened = _.flatten(arr); console.log(flattened); /* Output: [ 1, 2, 3, 4, 5 ] */ |
5. Using Lodash Library
The flatten method is also included in the Lodash library. To recursively flatten an array of any depth, use the _.flattenDeep` method.
|
1 2 3 4 5 6 7 8 9 10 |
const _ = require('lodash'); const arr = [[1,2],[3,[4,[5]]]]; const flattened = _.flattenDeep(arr); console.log(flattened); /* Output: [ 1, 2, 3, 4, 5 ] */ |
That’s all about recursively flattening a nested array of any depth in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)