Created
July 20, 2016 22:42
-
-
Save donaldparker/b11c778143f2cb1798d462f700f0a72b to your computer and use it in GitHub Desktop.
Array Flatten is JS
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 flatten(array) { | |
var result = []; | |
var nodes = array || array.slice(); | |
var node; | |
if (!array.length) { | |
return result; | |
} | |
node = nodes.pop(); | |
do { | |
if (Array.isArray(node)) { | |
nodes.push.apply(nodes, node); | |
} else { | |
result.push(node); | |
} | |
} while (nodes.length && (node = nodes.pop()) !== undefined); | |
result.reverse(); // we reverse result to restore the original order | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment