Search code examples
javascriptarraysflatten

Flatten array of multiple nested arrays without recursion - javascript


Maybe it's stupid question but I cannot realize is that possible to flatten multidimensional array without recursion?

I have one solution written by me with recursion:

function transform (arr) {
   var result = [];
   arr.forEach(flatten)
   function flatten (el) {
     if (Array.isArray(el)) {
        return el.forEach(flatten);
     }
     return result.push(el);
   }
   return result;
}

Example of an array to flatten:

[1, {a: [2, 3]}, 4, [5, [6]], [[7], 8, 9], 10]

And execution:

var a = [1, {a: [2, 3]}, 4, [5, [6]], [[7], 8, 9], 10];
var r = transform(r);
console.log(r); // [1, {a: [2, 3]}, 4, 5, 6, 7, 8, 9, 10]

Thanks!


Solution

  • You can use a stack. When you discover a nested array, just replace it with its items.

    function flatten(arr) {
      var result = [];
      var stack = arr, first;
    
      while (stack.length > 0) {
        first = stack[0];
    
        if (Array.isArray(first)) {
          // Replace the nested array with its items
          Array.prototype.splice.apply(stack, [0, 1].concat(first));
        } else {
          result.push(first);
          // Delete the first item
          stack.splice(0, 1);
        }
      }
    
      return result;
    }