Hello everybody!
I have been trying to understand how this algorithm works. And by using console.log() I’ve come to the conclusion that the spread operator is the one doing the job. But I don’t understand why or how.
I would have never thought of this solution even when I really like it. So I believe if I understand it well I will be able to think on this possibility in the future.
function steamrollArray(arr) {
let flat = [].concat(...arr);
return flat.some(Array.isArray) ? steamrollArray(flat) : flat;
}
steamrollArray([1, [2], [3, [[4]]]]);
This solution had the following code explanation. Which I don’t think it actually explains how it flattens the array, which I think it’s being done by the spread operator , or maybe I am just missing something:
Code Explanation
- Use spread operator to concatenate each element of
arr
with an empty array - Use
Array.some()
method to find out if the new array contains an array still - If it does, use recursion to call
steamrollArray
again, passing in the new array to repeat the process on the arrays that were deeply nested - If it does not, return the flattened array
I would really appreciate your help!
Thanks before hand