Last active
August 29, 2015 13:56
-
-
Save AmaiSaeta/9291862 to your computer and use it in GitHub Desktop.
[JavaScript] Array.flatten()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}, []); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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