Steamroller without recursive! using 'splice' and 'spread' operator =)

i want yours help to evaluate if this method may be called recursive or not , the test Steamroller agree it :

function steamrollArray(arr) {
for(let i=0;i<arr.length;i++){            //1
if(Array.isArray(arr[i])){                     //2
arr.splice(i,1,...arr[i])
if(Array.isArray(arr[i])){                     //3
i=i-1}                                           
}}
return arr
}

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

1 iterate trough array
2 if ‘arr[i]’ value is array ,replace at same position with spread operator’…arr[i]’
3 another ‘if’ function to check if ‘arr[i]’ still an array,if it’s not, back one step ‘i’ to reiterate trough the same index until ‘arr[i]’ became a non array value .
i dedicate this code to FreeCodeCamp Team =)
Test Link https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/steamroller

The function is not called inside of the function, so no, it isn’t recursive.

This will only work for arrays with two levels of depth.

i try it on multiple depth, it work well .

Oh. It’s working because of this. This is an anti-pattern with for loops.

1 Like