Steamroller Algorithm Clarification [Spoiler]

function steamrollArray(arr) {
  // I'm a steamroller, baby
  var flatArr = [];
  for (var x = 0; x < arr.length; x++) {
    if (Array.isArray(arr[x])) {
    // if item from arr is array 
      flatArr = flatArr.concat(steamrollArray(arr[x]));
      // recursively flatten array
    }
    else {
      flatArr.push(arr[x]);
      // push array items, non-arrays etc, to flatArr
    }
  }
  return flatArr;
}

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

Hi all

Can anyone explain this code to me

paticularly this line

flatArr = flatArr.concat(steamrollArray(arr[x]));

For example, with the test, steamrollArray([1, [2], [3, [[4]]]]);

what would be the ouput of flatArr if you where to log it after each recursive function call?

how exactly does the alrgorithm go from [1, [2], [3, [[4]]]] to [1,2,3,4]?

I have a follow up question, can someone explain to me, what happens with the index of the for loop when you go into the recursive calls o.O This is the only thing that bugs me with understanding recursion -.-

1 Like

Please don’t post spoilers without adding a tag to the topic. I added one for you.

  1. This code loops for the number of times required to ‘read’ the whole array.
  2. flatArr is an array that should be defined above the for loop.
  3. flatArr.concat(anotherArray) sticks two arrays flatArr and anotherArray together.
  4. flatArr = flatArr.concat(steamrollArray(arr[x])) sticks two arrays together, like the simple example above, but generates the second array by running the function that is currently being used again! This is what is meant by recursion. It’s not clear from your snippet, but this is actually all taking place inside a function called steamrollArray.

This is what the full function looks like, and it passes the tests.

Spoiler
function steamrollArray(arr) {
  var flatArr = [];
  
  for (var x = 0; x < arr.length; x++) {
    if (Array.isArray(arr[x])) {
    // if item from arr is array 
      flatArr = flatArr.concat(steamrollArray(arr[x]));
      // recursively flatten array
    }
    else {
      flatArr.push(arr[x]);
      // push array items, non-arrays etc, to flatArr
    }
  }
  return flatArr;
}
  1. i get that part,i’ve edited my question to make it more clear.
  2. also get that, i posted a shortened snippet. i’ve edited that also.
  3. i get what concat does in itself, but how it is it reducing the level of nesting for multi-level arrays? how does it go from [[4]]]] to 4?
  4. i get that steamrollArray is being called repeatedly with an array, until the base case stops the recursion. But, if you where to console.log flatArr after each call, what exactly would be it’s output?

Sorry, i realize my original question wasn’t very clear, my bad, i’ve actually already finished the exercise i was just looking for clarification, as i feel i don’t really understand my solution.