Flatten a nested array

Hey guys, I have a question regarding one of the challenges in the JavaScript course. I should flatten a nested array without using .flat(). I knew that I would need to use some kind of recursive function but in the end I could not come up with something that would be working properly. Because of that, I looked at the proposed solution and it was quite similar to mine with some differences.

I would like to ask what does this piece of code ...steamrollArray(arr[i]) do? I am quite familiar with spread operator and rest operator, but this time I do not know what is going on.

And I would like to ask why does not for loop in recursive function results in some kind of error. I thought that the recursive function would reset for loop to the beginning every single time and that would result in some kind of en error.

  **Proposed solution**
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
      flattenedArray.push(...steamrollArray(arr[i]));
    } else {
      // Copy contents that are not arrays
      flattenedArray.push(arr[i]);
    }
  }
  return flattenedArray;
};

// test here
steamrollArray([1, [2], [3, [[4]]]]);
  **Your browser information:**

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

Challenge: Steamroller

Link to the challenge:

I highly recommend against copying the answer. Habitually copying the answer will hurt your ability to problem-solve.

Instead, I would post your in-progress solution and we can help you fix it.


Iā€™m not sure what this means. Each function call is separate. The scope of all variables in each function call is independent.

I suspect that you may have some flaws in your understanding of variables, function calls, and scopes.

the function returns an array, the spread operator just do its usual thing on that array

1 Like

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