Tell us what’s happening:
When I place a console.log around the test function"steamrollArray([1, [2], [3, [[4]]]]);" it displays [1, 2, 3, 4], which is the desired output but the function will not pass the test after removing the console.log and running the test. I’m having a hard time understanding why the console.log of the function call would differ from the value it returns.
**Your code so far**
let flatArr = []
function steamrollArray(arr) {
for (let i = 0; i < arr.length; i++){
if(Array.isArray(arr[i])){
steamrollArray(arr[i])
}
else{
flatArr.push(arr[i])
}
}
return flatArr
}
steamrollArray([1, [2], [3, [[4]]]]);
**Your browser information:**
User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.41 Safari/537.36
You aren’t actually doing anything with the return value of the recursive function call. You can avoid ‘cheating’ the recursion by using the return value of steamrollArray()
I guess I thought it would kick the value to the else statement after it failed the Array.isArray() and push the value to flatArr. I need to think about this one a little longer and rework. thanks for the advice!
so technically it should be passing the first test still as is? but subsequent tests would fail as flatArr still contains the values from the first array it was passed?
Interesting! I didn’t think about a nested function. My solution was to have the main function push the spread of the recursion’s return to the result array:
const steamrollArray = arr => {
let r = [];
arr.forEach(i => r.push(...(Array.isArray(i) ? steamrollArray(i) : [i])));
return r;
}
I feel like yours might be faster since there’s no spread to worry about.
I don’t think that inner recursion is any faster than true recursion.
I always see inner recursion as an antipattern that patches a fix for faux recursion instead of fixing the problem with it.
Recursion is a functional programming idea. In functional programming you should have ‘pure’ functions that take inputs and produce outputs without any ‘side effects’ like modifying variables outside of the scope of the function. Faux recursion that fills up an external variable violates this idea.
Ultimately, this is an obfuscated while loop, which makes it harder to read and maintain.
While you should be proud of getting a solution that works, I’d take a look at the guide solutions for cleaner approaches.