Skip to content

Instantly share code, notes, and snippets.

@vicapow
Created March 1, 2015 10:59
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 vicapow/dd9ecbd76bb06f6551d7 to your computer and use it in GitHub Desktop.
Save vicapow/dd9ecbd76bb06f6551d7 to your computer and use it in GitHub Desktop.
non-recursive array flattening
var a = [1, 2, [2], [1, 2, [3, 4, [5]]], [[4, 5], 3, 2, 1], [1]];
function flatten(array) {
var stack = [];
var out = [];
var tail;
stack.push({array: array, idx: 0});
while(stack.length) {
tail = stack[stack.length - 1];
if (tail.idx >= tail.array.length) {
stack.pop();
} else if (tail.array[tail.idx] instanceof Array) {
stack.push({ array: tail.array[tail.idx++], idx: 0 });
} else {
out.push(tail.array[tail.idx++]);
}
}
return out;
}
console.log(flatten(a));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment