Steamroller - Clarification/help needed

Tell us what’s happening:
Hello Everyone,

I’m trying to solve the StreamRoller Challenge, but my solution is not passing the tests. I checked in Visual Studio Code and the result is the same inside the test.

I’m not asking for a working solution, I would ask for some guidance for what I’m doing wrong.

I don’t want to copy/paste or look-at existing solutions, because that way I will not learn :slight_smile:

Thanks in advance!

  **Your code so far**

//create resultArr
var resultArr = [];

function steamrollArray(arr) {
  //forEach to check the each array item
  arr.forEach(arrItem => arrFlat(arrItem));

  console.log("resultArr: ",resultArr);
  return resultArr;
}

function arrFlat(arrItem) {
    if(Array.isArray(arrItem)) {
         steamrollArray(arrItem);
    } else {
         resultArr.push(arrItem);
    }
};

steamrollArray([1, [2], [3, [[4]]]]);
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.192 Safari/537.36.

Challenge: Steamroller

Link to the challenge:

Your code contains global variables that are changed each time the function is run. This means that after each test completes, subsequent tests start with the previous value. To fix this, make sure your function doesn’t change any global variables, and declare/assign variables within the function if they need to be changed.

Example:

var myGlobal = [1];
function returnGlobal(arg) {
  myGlobal.push(arg);
  return myGlobal;
} // unreliable - array gets longer each time the function is run

function returnLocal(arg) {
  var myLocal = [1];
  myLocal.push(arg);
  return myLocal;
} // reliable - always returns an array of length 2

Thanks, but now it’s creating new instances of resultArr whenever I call steamrollArray inside my arrFlat function. So this way it’s not good either.

New Code:

function steamrollArray(arr) {
  //create resulArr
  let resultArr = [];

  //loop through the arr variable
  arr.forEach(function arrFlat(arrItem){
    //Check if arrItem is an array or not
    if(Array.isArray(arrItem)){
      //If it's an array call steamrollArray again
      steamrollArray(arrItem);
    } else {
      //If not, push to resultArr
      resultArr.push(arrItem);
    }
  });
  
  console.log("resultArr:",resultArr);
  return resultArr;
}

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

//This is the result:
/*
resultArr: [ 2 ]
resultArr: [ 4 ]
resultArr: []
resultArr: [ 3 ]
resultArr: [ 1 ]
*/

Well, with this you are throwing away the array on each function call. You should use return in your function. I’d look back at the recursion Challenges to refresh your memory.