Steamroller | Intermediate Scripting

Hi,

Following is the unsolved code for Steamroller -

function steamrollArray(arr) {
  let flatArray = [];
  for (let i = 0; i < arr.length; i++){
    if(Array.isArray(arr[i])){     
       steamrollArray(arr[i]);    
        
    } else{
      console.log(arr[i])
      flatArray.push(arr[i])    
    }    
  } 
  console.log(flatArray)
return flatArray;  
}

steamrollArray([1, {}, [3, [[4]]]]);

So when I did console.log for arr[i], I get the items I have to pass into the flatArray. However, when I push them, flatArray isn’t displaying the exact same pushed items and the order in which they were pushed are off too.

Following is the link to the problem-

Thanks,
Deeti

This is your issue here. You aren’t doing anything with the return value from this recursive call.

This is your issue here. You aren’t doing anything with the return value from this recursive call.

I think, I am calling it again until I find an element inside an array. If I find it I will push it to flatArray. Not sure if I understanding why we need a return value here. Sorry :frowning: but I need more explanation to understand better.

Thanks for getting back,
Deeti

Each function call has its own separate scope.

To put it another way, the flatArray in the recursive call is a different flatArray than the one in the parent call.

This will take some time to wrap my head around with.
Thanks for getting back. Your explanation was useful.

Function scope is one of those pieces that makes recursion a bit tricky to get used to.

Then how can I get more use to of this concept? This is first of kind problem where I am getting to know when I make a recursive call, a new scope will be created every time. It will have variable names with the same names as the global one, but it will refer to to the ones inside them.
Interesting functionality though!
Thanks

The same thing happened in these two challenges:

though these challenges where a while ago

Right…Thanks!!!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.