# Flattening nested arrays

Flattening nested arrays
0

#1

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?

#2

What if you did not know in advance how deep it was? It would be incredibly inefficient to just keep iterating over an array extra times, because you put an arbitrary number like 20, 30, 40, 1000 for your for loop. What if the first outer array had 10,000,000 elements and only one of those had an nested array of two deep and your for loop was set up to loop 30 times? Your solution would be iterating through an array equivalent in size of 300,000,000 elements.

Think about how you could use recursion to solve the need to guess a proper number for loop as you describe.

#3

I mean, I understand it theoretically, but I guess I was thinking of it from more of a realistic actual situation point of view. But yes, you’re right. It would result in too many useless loops, which would hurt performance.

I should probably learn how to solve it with recursion for educational purposes anyway.