So I’m at the “Steamroller” algorithm and I’ve come up with a solution that I’m not too sure about, because I guess it isn’t exactly “clean”.
In the exercise we have to flatten a multidimensional array that has multiple levels. If it was only maximum one level deep, we can use:
arr.reduce(function(a, b) {
return a.concat(b);
},[]);
So for example, [1,2,[3,4],[5],[6]] would return = [1,2,3,4,5,6].
However, [1,2,3,4,5,[[6]]] would return [1,2,3,4,5,[6]];
I understand the problem. But why can’t I just run a for-loop over it a couple times to flatten it completely?
I looked at all the other solutions (at least the basic ones, not the intermediate difficult ones) and they seem “cleaner”, but running a for loop over this function that i mentioned seems much simpler and shorter.
This is my solution:
function steamrollArray(arr) {
for (var i = 0; i < 10; i++) {
arr = arr.reduce(function(a, b) {
return a.concat(b);
},[]);
}
return arr;
}
steamrollArray([1,2,[3,4],[5],[[6]]]);
I put i < 10, because no array is going to be deeper than that. And if it would be, i could just put a number like 20,30 or whatever, just in case.
Are there any downsides to a solution like this?