Intermediate Algorithm Scripting: Steamroller

Intermediate Algorithm Scripting: Steamroller
0.0 0

#1

My output matches what the test is expecting, but it fails all of the tests. :confused:

Link to the challenge: https://beta.freecodecamp.org/en/challenges/intermediate-algorithm-scripting/steamroller

Here is my output from the console. All output matches the listed expected output from the unit tests.

[β€œa”, β€œb”]
[1, 2, 3, 4]
[1, 3, 4]
[1, {…}, 3, 4]

Here is my code:

function steamrollArray(arr) {
  // I'm a steamroller, baby
  
  var bool = false; //track if an item is an array
  var newArray = []; //empty array to use with concat
  
  newArray = newArray.concat(...arr);//flatten the array

  
  //loop through the array and flag if an item is a nested array
  for (let i = 0; i < newArray.length; i++) {
     if (Array.isArray(newArray[i])) {
       bool = true;
     }        
  }
  
  //if bool = true for a value, recurse through function
  if (bool) {
    steamrollArray(newArray);
  } else { //otherwise return the value of newArray
    console.log(newArray);
    return newArray;
  }
  
}


steamrollArray([1, [2], [3, [[4]]]]);[/spoiler]

#2

You aren’t actually returning your final solution. Test it here.


#3

It looks like I was missing the return in the recursive function call. Changed it to the following and it works. I’m new to recursion, now I have to wrap my head around why I needed a return for the function call. Any help in explaining the details there would be much appreciated.

function steamrollArray(arr) {
  // I'm a steamroller, baby
  
  var bool = false; //track if an item is an array
  var newArray = []; //empty array to use with concat
  
  newArray = newArray.concat(...arr);//flatten the array

  
  //loop through the array and flag if an item is a nested array
  for (let i = 0; i < newArray.length; i++) {
     if (Array.isArray(newArray[i])) {
       bool = true;
     }        
  }
  
  //if bool = true for a value, recurse through function
  if (bool) {
    return steamrollArray(newArray);
  } else { //otherwise return the value of newArray
    return newArray;
  }
  
}


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

#4

I think I might get it now. Without the return it was just calling the function one time after the if statement when the value was true. That function call happened to result in the else code executing which is why I saw the correct values in the console, but the main function was not returning anything, just the single call to the function after the if was returning a value.

Is that correct?