Seemingly working code doesn't pass the test

Tell us what’s happening:

The code I wrote seems to do what it should do. At least when I output the tests with consol.log they all give the correct flattened arrays. However, the code does not pass the test. Can anyone see why it wouldn’t pass?
Is it possible that the arrays that it generates are invisibly different from the expected arrays?

I saw in the solutions that solution 1 is very similar to mine. But the recursive function has it’s own name and is called by the main function. To me that seems to be only an extra outer layer peeled of the recursion. Another difference is that it uses a ‘for…in’ loop in the recursion and the forEach loop in the main function. Is there an essential difference between the two?

Thanks in advance for looking at it and thinking along!
Niek

Your code so far


//declare global array to fill with the right elements
var resultArr = []

function steamrollArray(obj) {  //recursive flattening any array to basic elements
  
  if (!Array.isArray(obj)) {
    resultArr.push(obj);
  } else {
    obj.forEach(steamrollArray);      
  }

return resultArr;
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:81.0) Gecko/20100101 Firefox/81.0.

Challenge: Steamroller

Link to the challenge:

The difference that made the code pass the test is putting the recursive function declared as variable inside the main function. I don’t understand how that makes such a big difference. And the nested function stil feels as not using recursiveness to the fullest. Here is the code that passed:

function steamrollArray(arr) {
// declare empty arry for collecting flat objects
var resultArr = []

// recursive function flattening any array
var mySteamrollArray = function(obj) {
    
  if (!Array.isArray(obj)) {
      resultArr.push(obj);
    } else {
      obj.forEach(mySteamrollArray);
    }
  };


  arr.forEach(mySteamrollArray);
  return resultArr;

}

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

This here is the reason why your code was failing the tests.
Having a global variable means that new items keep getting added/modified the more times you invoke the function.

In general you want variables to be scoped to the function they belongs to.

Or practically with your code:

steamrollArray([1, [2], [3, [[4]]]])
steamrollArray([1])

// [ 1, 2, 3, 4, 1 ] 

You can see that the second invocation of your functions adds into an existing data set.

Thank you Marmiz! I had indeed tested all tests individually, not all four in one go. Then I would have seen the problem.

Besides the testing environment, you should never rely on global variables, I hope this little misfortune thought that :slight_smile:

Happy coding!

1 Like