Steamroller Challenge, problem with return statements

Tell us what’s happening:
Describe your issue in detail here.

I have two variations of code, one where the return statement is within the if statement, and another where the return arr is within the else statement.

These both cause issues, but I’m unsure how to resolve them. In case 1: if,
the code returns undefined for my output, even though it will log the correct output immediately beforehand. For example,

[ 1, 2, 3, 4 ]
undefined

I have no idea what’s going on here as it is logging the correct output, but when returning it immediately afterwards, it will be undefined.

In the second case, where the return is within the else statement, the code will return the old arr, the one not manipulated by the other nested calls. For example, the output in this case will be:

[ 1, 2, 3, 4 ]
[ [ 2 ], [ 3, [ [Object] ] ], 1 ]

In this case, I would like to return the arr in the previous iteration of the nested call. But I’m not sure how to tackle this, I’ve tried storing it as a separate variable to return it later, but it doesn’t work either. I’m not too sure how to approach this issue and any help would be appreciated!

  **Your code so far**


function steamrollArray(arr){
let flag = true;
for (let i = 0; i<arr.length;i++){
  if (Array.isArray(arr[i])==true){
    flag = false;
  }
}
if (flag == true){
  console.log(arr)
  return arr
} else { 
  arr=arr.concat(arr[0])
  arr.splice(0,1)
  console.log(arr)
  steamrollArray(arr)

}

}

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



  **Your browser information:**

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

Challenge: Steamroller

Link to the challenge:

You want a return in both the if and the else. It’s just going to return different things. It’s similar to when you solved the recursive countdown challenge.

1 Like

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