Below is the example of the Array flat() method.
// Creating multilevel array
const numbers = [[
const flatNumbers= numbers.flat(Infinity);
The arr.flat() method was introduced in ES2019. It is used to flatten an array, to reduce the nesting of an array.
Parameters: This method accepts a single parameter as mentioned above and described below:
- depth: It specifies, how deep the nested array should be flattened. The default value is 1 if no depth value is passed as you guess it is an optional parameter.
Return value: It returns an array i.e. depth levels flat than the original array, it removes nesting according to the depth levels.
More codes for the above function are defined as follows:
Program 1: The following code snippet shows, how flat() method works.
Zero levels flattened array: [1, [2, 3], [], [4, ], 6] One level flattened array: [1, 2, 3, , 4, , 6] Two levels flattened array: [1, 2, 3, 4, 5, 6] Three levels flattened array: [1, 2, 3, 4, 5, 6]
Note: For depth greater than 2, array remains the same, since it is already flattened completely.
Program 2: We can also remove empty slots or empty values in an array by using flat() method.
[1, 2, 3, 4]
- Google Chrome
- Mozilla Firefox
- Microsoft Edge
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.