Steamroller code isn't working

This code isn’t passing any of the test cases even the answers come out to be correct in a different compiler.

let n = [];

function steamrollArray(arr) {
    
for(var i = 0; i<arr.length;i++){
    
    if(Array.isArray(arr[i]))
        { steamrollArray(arr[i]);}
        //n = n.concat(a);}
    else
      n.push(arr[i]);//console.log(n);}
}
  return n;}
console.log(steamrollArray([1, [2], [3, [[4]]]]));

Check now. I had originally declared it but forgot to copy it.

Ok I get it. It actually does works on other compilers but to pass the test I have to declare it locally and update it’s value accordingly.

Hi,

I see a couple of possibilities that might work for you.

Array n needs to be declared inside your steamrollArray function (or at least re-initialized to [ ] inside function ) no matter what you do. Otherwise the return value from final test will look like this [ 1, 2, 3, 4, 'a', 'b', 1, 3, 4, 1, {}, 3, 4 ]

One possibility is to wrap your recursive function and array n inside steamrollArray.
That would recreate a new array n every test and all of your recursive calls could access the same array like you are doing already.


function steamrollArray(arr){
    const n = []; //declared local to function

   function myFunc( array ){
      // flatten code here
     // call myFunc recursively until elements are not array
     else  n.push(element)
   }

   myFunc(arr);
   return n;
}

Another possibility would be to keep your code mostly as it is but without a global array n you will need to do something with return value of the recursive function calls.

if(Array.isArray(arr[i])){
         steamrollArray(arr[i]);  // you are calling steamrollArray but you are doing nothing with the return value
                                  // you'll have to use push or concat or something to add that to array n
}