Steamroller Working but not passing the run test

Steamroller Working but not passing the run test
0

#1

Tell us what’s happening:
Here’s my solution and it does work (for all the cases as given on FreeCodeCamp for this challenge), but when I run to test it, it doesn’t pass. I’ve tried all the following cases, and it does return the right values, but none of the tests pass when I run test on FreeCodeCamp.

steamrollArray([[[“a”]], [[“b”]]]) should return [“a”, “b”].
steamrollArray([1, [2], [3, [[4]]]]) should return [1, 2, 3, 4].
steamrollArray([1, [], [3, [[4]]]]) should return [1, 3, 4].
steamrollArray([1, {}, [3, [[4]]]]) should return [1, {}, 3, 4].

Your code so far

let vals = [];

function steamrollArray(arr) {
  
  arr.forEach((val) => {
    if (Array.isArray(val)){
      steamrollArray(val);
    } else {
      vals.push(val);
    }
  });
  
  return vals;
}


steamrollArray([[["a"]], [["b"]]]);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86.

Link to the challenge:


#2

Challenges generally won’t pass if you used global variables.

You’ll have to do a bit of rewrite so your code doesn’t use globals.


#3

Yeah I thought so, using global variables might not be an appropriate solution, but I guess then there should be a note (or a condition) on that on the challenge page. (because otherwise the solution still meets all conditions specified by FCC.) Anyways, thanks though.

This worked for me:

function steamrollArray(...arr) {
  
  let vals = arr[1] ? arr[1] : []; 
  
  arr[0].forEach((val) => {
    if (Array.isArray(val)){
      console.log(vals);
      steamrollArray(val, vals);
    } else {
      vals.push(val);
    }
  });
  
  return vals;
}

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