Hello everyone, I just made this challenge work, but I don’t understand why it works? I’m looping through the items of my array for (let item of arr) and then without using the item which is my variable i made it work. I hope you understand what I mean and help me to understand how come this can work. Thanks.

function steamrollArray(arr) {
if(Array.isArray(arr)){
for (let item of arr)
arr = arr.reduce((a,b)=> a.concat(b), []);
}
return arr;
}
steamrollArray([1, [2], [3, [[4]]]]);

Browser information:

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

We have blurred this solution so that users who have not completed this challenge can read the discussion in this thread without giving away the solution.

I believe if you wrote any for loop (a while loop or for) that repeats the exact number of times the arr length is, it will still work the same.

Eg

for (let i=0;i<arr.length;i++) will work

And you are modifying the array each time by flattening out one layer of depth. So if the array started out with a depth of 5, you are reducing that by one each time the loop runs. (So item has no value here at all)

A bit late but if the array is too deep this won’t work: steamrollArray([1, [], [3, [[[4]]]]]) already returns [ 1, 3, [ 4 ] ]

some leftovers of my mathematic studies:
let’s say there was a solution only dependent on the length of the array.

Then there would exist a natural number n that is the maximum of iterations said solution needs to solve the problem for every depth that an array with a fixed length may have.

There would also exist a natural number m that is the maximum each iteration reduces the depth of the array (if there wasn’t a maximum it wouldn’t be dependent on the length)

=> the solution can’t flatten an array with a depth greater than n * m