Skip to content

Instantly share code, notes, and snippets.

@viruschidai
Created August 28, 2017 01:36
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 viruschidai/d66bf628c6a9ab6e09e12582d516a082 to your computer and use it in GitHub Desktop.
Save viruschidai/d66bf628c6a9ab6e09e12582d516a082 to your computer and use it in GitHub Desktop.
Flatten js array without recursion
function flatten(arr) {
if (!arr || !arr.length) return [];
var nodes = arr.slice();
var results = [];
var node = nodes.pop();
while(node) {
if (Array.isArray(node)) {
nodes.push.apply(nodes, node);
} else {
results.push(node);
}
node = nodes.pop();
}
return results.reverse();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment