This is just solution 2 provided. Its very simple and uses recursion but even after carefully going through the explanation I still don’t understand it.
Can someone give me a step by step run through of an example?
function steamrollArray(arr) {
var flat = [].concat(...arr);
return flat.some(Array.isArray) ? steamrollArray(flat) : flat;
}
console.log(steamrollArray([1, [2], [3, [[4]]]]));
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36.
Just because the solution is small doesn’t mean it is simple. There is a lot of information packed into that function!
function steamrollArray(arr) {
let flat = [].concat(...arr); // This is the magic here
if (flat.some(Array.isArray)) {
return steamrollArray(flat);
} else {
return flat;
}
}
console.log(steamrollArray([1, [2], [3, [[4]]]]));
// What does this do?
console.log([].concat([1], [2], [3]);
// And how about this
console.log(...[[1], [2], [3]]);
I guess simple wasn’t the right word. I really meant concise.
So when you recursively call the function again on “flat” does it copy the outermost array element into the new array? Like it will copy 1, then 2, then 3, etc?
This is the part I don’t understand.
Okay that is starting to make more sense.
The spread operator + concat copies the top level subarrays?
I also think I was getting confused with this particular example array cause the first element was just a digit, the second element is a single element array and then the third element is a nested array. It kind of threw me off!