Need Help Understanding Solution 1 of Steamroller

This function is to flatten an array with nested arrays inside:

function steamrollArray(arr) {
  const flattenedArray = [];
  // Loop over array contents
  for (let i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      // Recursively flatten entries that are arrays
      //  and push into the flattenedArray
    } else {
      // Copy contents that are not arrays
  return flattenedArray;

// test here
steamrollArray([1, [2], [3, [[4]]]]);

Why do we use the spread (…) in line 5? What does it actually do to the input? I wrote the whole thing without it but couldn’t understand how I would know to use it!


This solution was from the forum post for this exercise

Can you explain a little more what you need help understanding?

Ahhh, sorry, I see you included that after code. It just didn’t stick out enough form me to see. My bad.

That line is making a recursive call to steamrollArray. What value does that function always return?

I’m thinking it is returning an array ? Do you always have to spread an array when using it as an input then?

That’s exactly right. So how does the push method work?

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