Last active
October 31, 2017 12:00
-
-
Save framp/1af26ee360f81c928ca1 to your computer and use it in GitHub Desktop.
Iterative flatten indefinite nested array
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(input) { | |
if (!input) return | |
var output = []; | |
while(input.length) | |
if(input[0] instanceof Array) | |
input.unshift.apply(input, input.shift()) | |
else | |
output.push(input.shift()) | |
return output | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@lifeamit depends on the language and how the array is built internally - most are contiguous, so adding onto the end often requires copying everything over to a new place in memory, anyway. This is versus a linked list where you can obviously just link to data anywhere else in memory without any issue. Please illuminate me if I'm missing something!