Code works but not passing the test

Tell us what’s happening:
I’ve looked through each example and as far as I can see, the result returned matched the test example. What could be the reason the test is not passing?

Your code so far


let array = [];
function steamrollArray(arr) {
for (let num of arr) {
  if (Array.isArray(num)) {
    steamrollArray(num);
  } else {
    array.push(num);
  } 
}
return array;
}

console.log(steamrollArray([1, {}, [3, [[4]]]]));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36.

Challenge: Steamroller

Link to the challenge:

Your code contains global variables that are changed each time the function is run. This means that after each test completes, subsequent tests start with the previous value. To fix this, make sure your function doesn’t change any global variables, and declare/assign variables within the function if they need to be changed.

Example:

var myGlobal = [1];
function returnGlobal(arg) {
  myGlobal.push(arg);
  return myGlobal;
} // unreliable - array gets longer each time the function is run

function returnLocal(arg) {
  var myLocal = [1];
  myLocal.push(arg);
  return myLocal;
} // reliable - always returns an array of length 2

In this case, I sometimes call this particular anti-pattern ‘faux recursion’. The code looks recursive, but you are using a global variable instead using the return value from each recursive call.

I understand now…
But if I declare the variable in my recursive function, it gets reset as it’s recurring.
Another problem I have is that in my recursive function, once it finds the value, it passes it back through the return, and returns a nested array, and not the values themselves. That’s why I was just pushing them outside once they were found.

Any way possible to make this work? Or is this just not a viable solution?

You can definitely make this work recursively.
I would take a peak at the spread operator.

I got it working. Thanks for your help! :+1:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.