Tell us what’s happening:
I wrote my function with several sanity checks to keep track of the array as it’s worked through each recursive step, and the final log of the array that should be returned appears to be showing the right answer. However, when I run the function in my console, the function returns undefined. I don’t understand why this is happening, especially since I am able to successfully log what appears to be the correct value in the line immediately before the return statement.
Your code so far
function steamrollArray(arr, safety = 0) {
// I'm a steamroller, baby
safety++;
var callAgain = false;
//console.log(arr, safety);
if (safety > 100) {
return("Safety exception");
}
var arrOut = [];
// For each element of the array
arr.forEach(function(elem) {
// If the element is an array
if (Array.isArray(elem)) {
// Flip switch to callAgain to true to call function again
callAgain = true;
// Push every sub-element of the array to arrOut
elem.forEach(function(subElem) {
arrOut.push(subElem);
});
} else {
arrOut.push(elem);
}
});
// If bad element caused callAgain to be flipped
if (callAgain == true) {
console.log("steamrolling again: ", "\narr: ", arr, "\narrOut: ", arrOut, '\n');
// steamroll arrOut
steamrollArray(arrOut, safety);
} else {
console.log("arrOut:", arrOut);
return arrOut;
}
}
steamrollArray([1, [2], [3, [[4]]]]);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/steamroller/