SteamrollArray: console.log() shows requested numbers and strings but I can not .push them into array

I have tested my code using console.log(arr) for the else function (Function 1) and it return the elements of the array, but I can not .push them into my result array (Function 2). I have used typeof(arr) in Function 3 to see whether the function returns numbers and strings which is does, so I am not sure, why I can not push the arr into result. Any help is appreciated!

Function 1


function steamrollArray(arr) {
var result = [];
if (Array.isArray(arr) === true) {
  for (const key in arr) {
    steamrollArray(arr[key]);
  }
} else {
  console.log(arr);
 }
}
steamrollArray([1, [2], [3, [[4]]]]);

Function 2


function steamrollArray(arr) {
var result = [];
if (Array.isArray(arr) === true) {
  for (const key in arr) {
    steamrollArray(arr[key]);
  }
} else {
result.push(arr);
 }
return result;
}
steamrollArray([1, [2], [3, [[4]]]]);

Function 3

function steamrollArray(arr) {
var result = [];
if (Array.isArray(arr) === true) {
  for (const key in arr) {
    steamrollArray(arr[key]);
  }
} else {
  console.log(typeof(arr);
  }
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:86.0) Gecko/20100101 Firefox/86.0.

Challenge: Steamroller

Link to the challenge:

You are redefining your result array on each function call and not doing anything with it. To solve this recursively, you need to return the flattened result on each level of recursion and use that result.

Iā€™d go back and look at the challenge where you create countUp and countDown arrays with recursion.

1 Like

Hi @JeremyLT , thank you very much for your help. That was an easy mistake I should have seen myself. I have been trying to follow your remarks, so far no luck even though I went back to the recursion lesson (and many other lessons). If I understand you correctly, I need to make changes to the else part, is that right? I am starting to doubt that the code in my for and if part is right as I have tried a lot of different approaches to follow your instructions.

In this attempt, Iā€™d look at changing your if clause. If your array entry is an array, how should you handle the contents to flatten them? You are right that calling steamrollArray is good, but you need to use the return value of the recursive function call.

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