One Pager Cheat Sheet
- This tutorial explains how to use the
flat()
function in Javascript to flatten nested arrays to a specificdepthLevel
and provides an example of how to implement your own version of this method. - We can recursively iterate through an array and
flat
it to the givendepthLevel
, while pushing anynon-array
element 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.
xxxxxxxxxx
11
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
Alright, well done! Try another walk-through.
If you had any problems with this tutorial, check out the main forum thread here.