Steamroller - working on local but not passed test on FCC

Hi, what’s wrong with my code? It passed all tests on local :face_with_symbols_over_mouth::face_with_symbols_over_mouth::face_with_symbols_over_mouth:

Your code so far


let resultArr = [];

function steamrollArray(arr) {
  // I'm a steamroller, baby
	for(let el of arr){
		if(!Array.isArray(el)){
			resultArr.push(el);
		} else {
			steamrollArray(el);
		}
	}
 	return resultArr;
 }


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

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux i686; rv:60.0) Gecko/20100101 Firefox/60.0.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/steamroller/

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
1 Like

Yep, thank you so much?

function steamrollArray(arr) {
  // I'm a steamroller, baby
  let resultArr = [];
  rollArray(arr);

  function rollArray(rArr){
		for(let el of rArr){
			if(!Array.isArray(el)){
				resultArr.push(el);
			} else {
				rollArray(el);
			}
		}
	}

 	return resultArr;
 }

passed this challenge but my code still seems odd, isn’t it? Can it be improved?

Code looks fine. I would move the call rollArray(arr); to after the function, not before it, as this a. is clearer (you define a function then use it, not use a function then define it), and b. is actually what happens (the function gets hoisted to the top of the scope then the function call occurs after)

1 Like