Steamroller - Recursive Code- Answer Correct but no test case passing

Tell us what’s happening:
I used a recursive approach to solve this problem and the answer is correct but no test cases are passing?

Your code so far


var requiredArray = []
function steamrollArray(arr) {
  // I'm a steamroller, baby
  for(let i = 0 ; i < arr.length ; i++){
        if(!Array.isArray(arr[i])){

            requiredArray.push(arr[i]);
        }
        else{

            steamrollArray(arr[i]);
        }

  }
  return requiredArray;
}

steamrollArray([[["a"]], [["b"]]]);



Your browser information:

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

Link to the challenge:

your answer is not correct. you have a global variable, that means that every time the function is called (and for the tests it is called many times), new items are added there. only the first function call will have correct result, the others will have other items at the beginning of tre array

1 Like

Could you pls suggest the changes in code I should do? :slight_smile:

try to refactor the code yourself without using a global variable

1 Like

Could you pls steer me in the right direction .
I was thinking of using the requiredArray as a parameter :slight_smile:

That’s fine, but steamrollArray only takes a single argument, so you have to provide a default else it won’t work (i.e. steamrollArray (arr, requiredArray = []) {). Then you can use requiredArray in subsequent recursive calls. And you’ll likely have to rethink how your loop works and what you’re returning.

You can also do the following. Your current code:

var requiredArray = []
function steamrollArray(arr) {
  // do stuff
}

to:

function steamrollArray(arr) {
  var requiredArray = []
  function originalSteamrollArray(arr) {
    // do stuff
  }
  originalSteamrollArray(arr);
}

Thanks Man , the idea worked :slight_smile:

1 Like