Flattening nested arrays

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;


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?

1 Like

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.

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.

How about my code ? Is there any downsides to this solution ?

function steamrollArray(arr) {
  if (arr.length == 0) return [];
  let c = arr.shift();

  if (typeof c == "object") {
    if (c instanceof Array == false) return [c, ...steamrollArray(arr)];
    return [...steamrollArray(c), ...steamrollArray(arr)];
  } else {
    return [c, ...steamrollArray(arr)];

let c = steamrollArray([1, {}, [3, [[4]]]]);

Hi @gasmillasuarez!

Welcome to the forum!

This post has not been active for three years. If you have a question about a challenge then please create a new topic.

Thank you!