Still having problems: SteamRoller: my recursion is wrong

Tell us what’s happening:
I still have two problems:

  1. My condition for pushing to the newArray is whether or not the element is an array, but because an empty array [ ] is still an array, my code looks inside the array for it’s first element which is undefined. So I am pushing ‘undefined’ to my newArray instead of ‘[ ]’.

If element is ‘[ ]’, Array.isArray([ ]) is true, so I recursively go to element[0], which is now undefined.

  1. I know that my recursive line of code:

flatten(e[0], finalArray)

only looks at the first element in an array e. I don’t get deep enough in my recursion.

when I try to ‘flatten’ [ 3 , [ [4] ] ], I only look at the first element in the array, the 3, but then ignore the 4 completely. I don’t know how to make that recursion look farther into the array [ 3 , [ [4] ] ].

Please help guide my thinking.

Your code so far

function steamrollArray(arr) {
let finalArray = [];
arr.forEach(e => flatten(e, finalArray));
return finalArray;

function flatten(e, finalArray) {
console.log(e, finalArray);
if (e == "[]") {console.log(true)}
if (!Array.isArray(e)) {
  console.log('pushed ', e);
} else {
    flatten(e[0], finalArray)

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

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Safari/605.1.15.

Challenge: Steamroller

Link to the challenge:

Hi I’ve had trouble solving this challenge too. But then I figured out how to do.

My thinking is for each element in the given array, if it’s an array (you can use isArray method), call the function steamrollArray while passing that element as parameter, otherwise push that to returned array.

Another tricky thing is that when you use recursive method, they need to push to the same array. So it should be a parameter in the function too. Then you can write it in this way "function steamrollArray(arr,newArr=[]) ". It means that newArr’s default value is . If we don’t specify we will just use default value.

Hope it helps!

1 Like