Flatten a nested array. You must account for varying levels of nesting

Tell us what’s happening:
Describe your issue in detail here.
Can someone explain the purpose of 3 dots ‘…’ before the steamrollArray function? And how is this possible that a recursive function is not returning a value. I mean how will the calls unwind?

  **Your code so far**

function steamrollArray(arr) {
var newArr = [];
for (var i = 0; i < arr.length; i++) {
  if (Array.isArray(arr[i])) {
    newArr.push(...steamrollArray(arr[i]));
  } else {
    newArr.push(arr[i]);
  }
}
return newArr;
}

console.log(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/92.0.4515.131 Safari/537.36

Challenge: Steamroller

Link to the challenge:

The return value of the function is an array, when it’s called, it’s an array. So you can use the spread operator because it’s an array.

My solution is:

function steamrollArray(arr) {
  let result = [...arr];

  while(result.some(item => Array.isArray(item))) {

    for(let i = 0; i < result.length; i++) {
      if(Array.isArray(result[i])) {
        result.splice(i, 1, ...result[i]);
      }
    }

  }

  return result;
}

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