Steamroller question: my function returns a flattened array but won't pass the tests

I can’t figure out why my code won’t pass the test. As far as I can tell it returns the correct flattened array but it doesn’t pass the tests…


var newArr = [];

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

var result= steamrollArray([[["a"]], [["b"]]]);

console.log(result);

  **Your browser information:**

User Agent is: Mozilla/5.0 (X11; CrOS x86_64 13904.55.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.102 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 for the quick and helpful response! Fixed it by declaring the variable within the function and modifying the recursive call to

 newArr.push(...steamrollArray(arr[i]));

Here’s the finished code:

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

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