Steamroller code isn't working

Steamroller code isn't working
0.0 0

#1

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]]]]));

#2

The line above references a variable named n, but you have not defined such a variable anywhere in your code. You can not use push on an undefined variable.


#3

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


#4

You can not use a global variable for n, because it will hold it’s value between the consecutive tests which are ran behind the scenes and cause the subsequent tests to fail.


#5

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.


#6

Not sure what you mean by other compilers. JavaScript is not a compiled language.


#7

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
}