Created
March 1, 2015 10:59
-
-
Save vicapow/dd9ecbd76bb06f6551d7 to your computer and use it in GitHub Desktop.
non-recursive array flattening
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
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