One Pager Cheat Sheet
- This tutorial explains how to use the
flat()function in Javascript to flatten nested arrays to a specificdepthLeveland provides an example of how to implement your own version of this method. - We can recursively iterate through an array and
flatit to the givendepthLevel, while pushing anynon-arrayelement directly into the result array.
This is our final solution.
To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.
xxxxxxxxxx11
function flat(array, depthLevel = 1) { let result = []; array.forEach((item) => { // if the item of the main array is an array itself, call the method recursively // to check the elements inside if (Array.isArray(item) && depthLevel > 0) { result.push(flat(item, depthLevel - 1)); } else result.push(item); // else, push the object into the result }); return result;}OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Got more time? Let's keep going.
If you had any problems with this tutorial, check out the main forum thread here.


