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;
}

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 Likes

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]]]]);
console.log(c);

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!

3 Likes