Steamroller question

Hello,

I can’t understand one thing in this tutorial, please see code below:

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

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

My question is: why code is not working without dots at the begining of recursive function call?

`````` flattenedArray.push(steamrollArray(arr[i]))
``````

If i wrote like this:

`````` flattenedArray.push(...steamrollArray(arr[i]))
``````

then everything works fine. As I understand, recursive function call should return same result and flattenedArray.push should simply push that result in array?

Thank You very much!

`steamrollArray` returns an array

in this way an array is being pushed to `flattenedArray`, so no flattening is appening

in this way the elements of the array are being pushed to `flattenedArray`

add `console.log` statements and look at the different outcomes with the different ways

1 Like

But in this case at second loop iteration:

``````flattenedArray.push(steamrollArray(arr[i])) //when arr[i] = [2]
``````

shouldn’t return and push to flattenedArray 2, and not an array?

I got it, it returns variable flattenedArray, which itself is an array, not a number.
Well, `[2]` is still an array, so it uses the spread operator to instead push the elements inside the array instead of the array itself