There are several situations in which the elements of an array are also an array. These types of arrays are known as nested arrays.
Previously, we had to use recursion to sort these kinds of arrays (nested arrays), which is quite tedious. So, to make this process easier, ECMA Script 2019 (ES10) introduced a new method known as
Array.flat() method is used to flatten an array. With the help of this method, we can un-nest (flatten) the nested array within a single line.
A flatten array is an array of depth 0. The flat method takes an argument, a number that represents the depth of an array. Depth is the number of nested arrays present inside an array.
- It returns a flattened array.
- The parameter depth is optional.
- The depth level specifies how deep a nested array structure should be un-nest (flattened).
- The default value of the depth parameter is 1.
var num = [1, [2, [3, [4, ]]]]; console.log(num.flat(2)); // output [1,2,3, Array(1)]
In the given example, we have created a nested array arr using var keyword of depth 4. This array consists of alphabets as its elements but in the form of the nested array. So, we are going to un-nest this array using
In the given output, there are three arrays. The first array occurs when we have flattened the array to the depth of 2.
The second array occurs when we have flattened the array till the depth of 3, and the third array occurs when we have flattened the array till depth 4.
In this lesson, we have learned about
array.flat() which was introduced in ECMA Script 2019 or ES 10. This method is used to flat the nested array in just a single line.