Flattening an array in JavaScript

If you have an mutidementional array(or nested array) you want to flattern, you can do it this way.

var flatten = function(array) {
  var result = [], self = arguments.callee;
  array.forEach(function(item) {
    Array.prototype.push.apply(
      result,
      Array.isArray(item) ? self(item) : [item]
    );
  });
  return result;
};

So now you can run it

//The result of
console.log(flatten([1,2,[3,4,[5,6]]]));
//Should be
[ 1, 2, 3, 4, 5, 6 ]

Leave a Reply

Your email address will not be published. Required fields are marked *