The operation of adding an inner array or nesting an array in normal array increments “1” in the depth level. For instance, with no nested array, a normal array will have a “0” depth level:
With one inner sub-array, the depth level will become “1”:
Similarly, increasing the number of inner sub-array will also increase the depth level:
[12, [23, [34, [45, 56, 67, 78]]]] // Depth level = 3
let flatArray= .concat(...array);
However, this approach only flattens the level one nested arrays:
let flatArray= .concat(...numArray);
The above-given code will add the inner array of “numArray” as a whole to “flatArray” as it cannot spread its elements:
Here, the “Array” object will invoke the “flat()” method while passing “depth” as an argument.
Now let’s check some examples to understand the stated concept.
Then, we will flatten the created nested “numArray” with the help of the “flat()” method:
In the following example, we will specify “2” as the “depth” level. Upon doing so the “numArray.flat()” will flatten the inner two sub-arrays and add their elements in the resultant “flatArray()”:
const flatArray= numArray.flat(2);
Execution of the given program will show the following output:
If you have no idea about the array depth level, pass “infinity” as an argument to the “Array.flat()” method. In this case, all sub-arrays elements are “recursively” concatenated into another array.
For instance, to flatten the below-given “numArray”, we will specify “infinity” in place of the depth level argument:
const flatArray= numArray.flat(Infinity);
As you can see, the “numArray.flat()” method has successfully flattened the nested “numArray”: