SteamrollArray challenge - not recursing deeply enough?

Tell us what’s happening:
I’m working on the Steamroller challenge in which we are to use recursion to flatten an array containing an unknown depth of nested arrays. With what I have written here, my function will flatten and return all values in the test cases EXCEPT the value of 4 which is nested within the final element of three of the test cases. I’ve tried plain old for loops using i or j to count up to the array length, I’ve tried for…of loops to iterate through all array elements. I’m not modifying the original array inside any loop. I’ve tried logging the array index and element values to the console. I don’t understand; why does it seem to be aware of the full array length, yet it exits the loop before iterating over the element that contains the nested 4?

Note: I did take a peek at the solutions but I would like to understand why my code doesn’t seem to be executing the loop as expected/intended.


Your code so far

function steamrollArray(arr) { 
let nested = [].concat(arr);
let output = [];
// console.log('nested is ', nested);
for (let x of nested) {
  // console.log('x of nested is ', x);
  // console.log('output ', output);
return output.filter(x => x); 

function recurse(element) {
// console.log('entered recurse with ',element);
if (!Array.isArray(element)) {
  // console.log('returning ', element)
  return element;
} else {
  // console.log(element , 'is array');
  for (let sub of element) {
    // console.log('passing in ', sub);
    return recurse(sub);

console.log(steamrollArray([[["a"]], [["b"]]]));
console.log(steamrollArray([1, [2], [3, [[4]]]]));
console.log(steamrollArray([1, [], [3, [[4]]]]));
console.log(steamrollArray([1, {}, [3, [[4]]]]));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36.

Challenge: Steamroller

Link to the challenge:

Computers are not aware of anything they just silently execute your script line by line:

for (let sub of element) {
    return recurse(sub);

Here you explicitly ask computer to return the first item of the array

This might help you with both functions:

Good luck!

1 Like

Thanks, that was it!

I changed how I was doing it, so that instead of returning a value from inside a function, I just pushed the value onto the new flattened array. This time I ended up with

function steamrollArray(arr, flattened=[]) {
  arr.forEach((x) => !Array.isArray(x) ? flattened.push(x) : steamrollArray(x, flattened));
  return flattened;