Skip to content

Instantly share code, notes, and snippets.

@hgupta
Created December 31, 2015 06:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hgupta/0e98739b57039dc1dfe9 to your computer and use it in GitHub Desktop.
Save hgupta/0e98739b57039dc1dfe9 to your computer and use it in GitHub Desktop.
Pure JavaScript (JS) Array Flatten method (like Ruby Array#flatten)
Array.prototype.flatten = function(limit) {
var level = 0;
if(limit === undefined) limit = Number.POSITIVE_INFINITY;
if(arguments.length > 1) level = arguments[1];
return this.reduce(function(a, b) {
if((b instanceof Array) && level < limit)
a = a.concat(b.flatten(limit, level + 1));
else
a.push(b);
return a;
}, []);
};
console.log([1, 2, 3].flatten()); // => [1, 2, 3]
console.log([[1], 2, 3].flatten()); // => [1, 2, 3]
console.log([[1], 2, 3].flatten(1)); // => [1, 2, 3]
console.log([[[1]], 2, 3].flatten(1)); // => [[1], 2, 3]
console.log([[[[[1]],2]],3].flatten(1)); // => [[[[1]], 2], 3]
console.log([[[[[1]],2]],3].flatten(2)); // => [[[1]], 2, 3]
console.log([[[[[1]],2]],3].flatten(3)); // => [[1], 2, 3]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment