# Intermediate Algorithm Scripting - Steamroller

Hi,

please can someone walkthrough the solution for me to aid my understanding of recursion?

``````function steamrollArray(arr) {
const flattenedArray = [];  // create new Array
for ( let i = 0; i < arr.length; i++) {    // loop through elements in array
if (Array.isArray(arr[i])) { // condition // arr is passed as an argument to is array to check if its an array
flattenedArray.push(...steamrollArray(arr[i])); // push  elements that are arrays to flattened arrays. but not sure i understand the use of rest here.  does this basically call the steamroll function which calls the loop ?
} else {
flattenedArray.push(arr[i]); // push non-array elements
}
}
return flattenedArray;
}

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

User Agent is: `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36`

Challenge: Intermediate Algorithm Scripting - Steamroller

Here are all the steps the program uses to complete

1. Parent Call

The parent function (or the function that is called first) creates a return array and the searches through all the indexes of the original array

2. Forward Recursion

The program then reaches first condition, isArray(), and any array are put back into the function, but since you are only giving it a index, your array loses a bracket (ex: [[5]] becomes [5] because index 0 is [5], losing a bracket)

3. Backward Recursion

The reason you use the spread operator on your push is because you are taking an array apart. You haven’t actually gotten rid of the brackets on the array, you were just moving deeper into it. The spread operator tears it apart. Your functions return an array that doesn’t have any arrays in it because of the conditional.

4. Here is the function with input [[[5], 6]]:

• Forward Recursion: Parent([[5], 6] 1st([5]) 2nd(5)(it skips to 5 because it is array)
• Backward Recursion: 2nd(5) 1st([5, 6]) Parent([5, 6])

I not a complete expert on recursion, but I hope this is helpful.

In recursion you write two cases

``````1.  Stop condition
// here you return some value from the function

2. Recursive condition
// you call the function with changed arguments and do something with returned value (i.e. when stop condition meets for the arguments provided)

``````

In this case this is the recursive condition,
whenever you get an element which is Array you pass that element to steamrollArray function and push the result of that to flatenedArray of parent function

This image might help to understand the internal working of recursion .

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