Skip to content

Instantly share code, notes, and snippets.

@framp
Last active October 31, 2017 12:00
Show Gist options
  • Save framp/1af26ee360f81c928ca1 to your computer and use it in GitHub Desktop.
Save framp/1af26ee360f81c928ca1 to your computer and use it in GitHub Desktop.
Iterative flatten indefinite nested array
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
}
@lifeamit
Copy link

lifeamit commented Nov 27, 2016

Unshifting is very expensive. It is better to operate at the end of the array (rather to modify it at beginning).

@ksatia
Copy link

ksatia commented Mar 3, 2017

@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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment