Skip to content

Instantly share code, notes, and snippets.

@AmaiSaeta
Last active August 29, 2015 13:56
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 AmaiSaeta/9291862 to your computer and use it in GitHub Desktop.
Save AmaiSaeta/9291862 to your computer and use it in GitHub Desktop.
[JavaScript] Array.flatten()
function flattenArray() {
return this.reduce(function(lhs, rhs) {
// lhs is already flatten.
if((rhs instanceof Array) && rhs.some(Array.isArray)) rhs = flattenArray.call(rhs);
return lhs.concat(rhs);
}, []);
}
function test() {
Array.prototype.flatten = flattenArray;
Logger.log([].flatten());
Logger.log([1].flatten());
Logger.log([1,2].flatten());
Logger.log([1,2,3].flatten());
Logger.log([[1],2].flatten());
Logger.log([1,[2]].flatten());
Logger.log([1,[2,3]].flatten());
Logger.log([[1,2],3].flatten());
Logger.log([[1,2],[3,[4,5]]].flatten());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment