So, here is a sample solution to solve the problem of flattening an array. My question is not 'how' to flatten the array. Rather, I am trying to understand some underlying functionality occurring in this recursion.
This solution goes through each element of the original array, breaking down any elements that are arrays by putting them back through the function until they are no longer arrays and can be pushed to the new array.
My question is, how does the 'for' loop keep track of all of the times that an element is put back through the function, and also continue looping through the rest of the 'original' array that it is working on at the time? It must be keeping track somehow otherwise every time an element is an array and is put back through, the current loop would be cut short. Hope my question makes sense.
function steamrollArray(array) {
var flatArray = [];
flatten(array);
function flatten(array) {
for (var i = 0; i < array.length; i++) {
if (Array.isArray(array[i])) {
flatten(array[i]);
} else {
flatArray.push(array[i]);
}
}
}
return flatArray;
}
steamrollArray([1, [2], [3, [[4]]]]);