Skip to content

Instantly share code, notes, and snippets.

@getify
Created October 21, 2011 16:38
Show Gist options
  • Save getify/1304287 to your computer and use it in GitHub Desktop.
Save getify/1304287 to your computer and use it in GitHub Desktop.
function flatten_array(arr) {
var i;
for (i=0; i<arr.length; ) {
if (Object.prototype.toString.call(arr[i]) == "[object Array]") {
// prepend `splice()` arguments to `tmp` array, to enable `apply()` call
arr.splice.apply(arr,[i,1].concat(arr[i]));
continue;
}
i++;
}
return arr;
}
flatten_array([1,2,[3,[4,5],[],6,[[[7]]]]]); // [1,2,3,4,5,6,7]
@notmasteryet
Copy link

// no recursion
function flatten_array(arr) {
  var i, tmp;

  for (i=0; i<arr.length; ) {
    if (arr[i] instanceof Array) {
      // prepend `splice()` arguments to `tmp` array, to enable `apply()` call
      arr.splice.apply(arr,[i,1].concat(arr[i]));
      continue;
    }
    i++;
  }

  return arr;
}

flatten_array([1,2,[3,[4,5],[],6,[[[7]]]]]); // [1,2,3,4,5,6,7]

@getify
Copy link
Author

getify commented Oct 21, 2011

@notmasteryet

nice idea, but i don't think it works fully correctly (doesn't handle nested deep i don't think?). try this input:

flatten_array([[[],[1,2]],[[[3]]]]); // should get: [1,2,3], instead: [[],1,2,[[3]]]

my version doesn't work with that input either. still trying to debug it.

@getify
Copy link
Author

getify commented Oct 21, 2011

i fixed it, i think.

@notmasteryet
Copy link

@getify, mine is working for any level of nesting :)

@notmasteryet
Copy link

.. did you copy only portion of the code?

@getify
Copy link
Author

getify commented Oct 21, 2011

sorry, must have missed something, seems to work. thanks! updating my snippet now accordingly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment