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.

Download  Run Code

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.

Download  Run Code

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.

Download  Run Code

4. Using Underscore Library

Underscore JavaScript library offers the _.flatten method, which can flatten a nested array of any depth.

Download Code

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.

Download Code

That’s all about recursively flattening a nested array of any depth in JavaScript.