Parameters: This function contains two parameters which are listed below:
- array: This parameter is used to hold the array elements.
- shallow: It is used to flattened an array into single level.
Return value: It returns the flattened array either one level or all levels.
Passing a list without shallow parameter _.flatten() function: The _.flatten() function is used to make the nested array flattened. It will take the array and remove all its depth to make it at 1 level. Since, the second parameter is not given so the all it’s depth will be reduced.
Passing the second parameter to the _.flatten() function: Passing the second parameter to the function so the n depth array will be flattened to n-1 depth. In the below example, the elements 1, 2 and 3 are enclosed inside only 1 bracket so they will no depth. The element 4 has 2 depths in the given array so it will have only 1 depth now and hence it will not be seen with the 1, 2 and 3 elements. the 5 element has 3 depth so in the resultant array will have 2 depth. Similarly, depth of 6th element is 6. And the last element 7 has 5 depth so it will be displayed at the inner most array.
Another Example using shallow parameter: In this example element 1 has depth 1 so it will be displayed at the starting level along with an array of 2 elements. The 1st element contains 2 element, where as the second element again has 2 elements. The first element is the 3 and the second also is having 2 elements in an array. Likewise the array also has 4 and an array of elements. Keep going like this, then the final array will contain element 7.
Another example to the _.flatten() function with shallow parameter: In this example the elements 1, 4, 6 can be seen at the first level as their depth is 1. Other than these the first level contains an array of 2 elements and 2 arrays of 1 element each. The array of size 2 contains element 2 and 3 at the next level. One of the array of one size contains 5 and the other contains 7 at the next level as their original depth was 2.
- jQuery | one() with Examples
- Underscore.js | every() with Examples
- jQuery | val() with Examples
- jQuery | on() with Examples
- jQuery | last() with Examples
- Underscore.js | map() with Examples
- jQuery | after() with Examples
- jQuery | eq() with Examples
- jQuery | first() with Examples
- Underscore.js | contains() with Examples
- jQuery | has() with Examples
- Underscore.js | some() with Examples
- Underscore.js | max() with Examples
- Underscore.js | _.last() with Examples
- Underscore.js | first() with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.