I've been studying recursive functions and I'm starting to understand them more or less. I was working on a free code camp challenge when I came across this and I do not understand it. A recursive function inside of a for loop:
function steamroller(arr) {
var newArr = [];
for (var i = 0; i < arr.length; i++) {
//If (i)th element is an array
if (Array.isArray(arr[i])) {
newArr = newArr.concat(steamroller(arr[i]));
console.log(newArr);
} else {
newArr.push(arr[i]);
}
}
return newArr;
}
steamroller([1, [2],[3, [[4]]]]);
//returns [1, 2, 3, 4]
The line I'm having a hard time understanding is:
newArr = newArr.concat(steamroller(arr[i]));
On that line, newArr is concatenated to what? The function is called again inside of the .concat method, right? But what happens to that for loop? Does the function call inside of the concat method force the loop to exit?
Here is a JSFiddle, I have each newArr logged to console, but I can't even follow it. The array is built up like so:
[1, 2]
[4]
[3, 4]
[1, 2, 3, 4] //Final
Thanks.
arris an Array, a recursive call is made on that array. SonewArris concatenated to what your recursive procedure returns on that element array (arr[i], for somei).flatten... Am I missing something?newArr.concat(steamroller(arr[i]));is concatinatingnewArrwithsteamroller(arr[i])and returns a new array. this has to be assigned to a varibale for using.