Iterative Array Flatten

Benchmark created by Tomalak on


Setup

var input = [1, {a: 2}, [3], [[4, 5], 6], 7];
  
  function flatten_JamesWilkins(input) {
      var i, placeHolder = [input], lastIndex = [-1], out = [];
      while (placeHolder.length) {
          input = placeHolder.pop();
          i = lastIndex.pop() + 1;
          for (; i < input.length; ++i) {
              if (Array.isArray(input[i])) {
                  placeHolder.push(input);
                  lastIndex.push(i);
                  input = input[i];
                  i = -1;
              } else out.push(input[i]);
          }
      }
      return out;
  }
  
  function flatten_georg(inp) {
      var out = inp.slice();
      while(out.some(Array.isArray))
          out = [].concat.apply([], out);
  }
  
  function flatten_tomalak(arr) {
      var state = [], s, a, i, output = [];
      state.push([arr || [], 0]);
      while (state.length) {
          s = state.pop();
          for (a = s[0], i = s[1]; i < a.length; i++) {
              if (Array.isArray(a[i])) {
                  state.push([a, i + 1]);
                  state.push([a[i], 0]);
                  i = a.length;
              } else {
                  output.push(a[i]);
              }
          }
      }
      return output;
  }
  
  function flatten_joews(input) {
    var output = [];
    var todo = [input];
    var current;
    var head;
  
    while(todo.length) {
      var current = todo.shift();
      if(Array.isArray(current)) {
        current = current.slice();
        head = current.shift();
        if(current.length) {
          todo.unshift(current)
        }
  
        todo.unshift(head);
      } else {
        output.push(current);
      }
    }
  
    return output;
  }

Test runner

Ready to run.

Testing in
TestOps/sec
James Wilkins
flatten_JamesWilkins(input);
ready
georg
flatten_georg(input);
ready
Tomalak
flatten_tomalak(input);
ready
joews
flatten_joews(input);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.