Steamroller gets same results but fails checker tests

Tell us what’s happening:

I am working on the Intermediate Algorithms “SteamRoller” program. I thought I solved it using recursion and I get all of the same results as what the tests indicate they should be, but the code checker says it is failing on each of those…? The only thing I can see that I might be getting dinged on is using a global variable? Can anyone look at my solution and give me a hint where I’m going wrong with this and why the checker is failing me on each test?

Cheers

Possible spoiler below
Your code so far


let flattenedArray = [];

function steamrollArray(arr) {
// I'm a steamroller, baby
   while(arr.length >= 1)  {
      if( !(Array.isArray(arr[0]))) {
          let lastElement = arr.shift();
          flattenedArray.push(lastElement);
      }
      else {
          steamrollArray(arr[0]);
          arr.shift();
      }
  } 
  return flattenedArray;
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36.

Challenge: Steamroller

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/steamroller

@opalko I suggest getting rid of the global variable.

You could add a second parameter to your function named flattenedArray. When you make the recursive call, make sure to include the variable as the 2nd argument.

You may ask how you assign an empty array to flattenedArray in the first call. There are two approaches. You can check if flattenedArray has a value and assign it an empty array if it does not. The other way is to use a default function parameter for the flattenedArray parameter with the value of an empty array.

1 Like

That’s exactly what I didn’t know how to do and why I used a global! Thanks, works great now!
Cheers