Created
December 9, 2015 20:35
-
-
Save toddbranch/e4b77e2aef996ca13b59 to your computer and use it in GitHub Desktop.
Flatten 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
// this implementation preserves the original arr | |
function flatten(arr) { | |
var result = []; | |
var queue = []; | |
var pointer = 0; | |
while(pointer < arr.length) { | |
queue.push(arr[pointer]); | |
pointer += 1; | |
while(queue.length > 0) { | |
var current = queue.shift(); | |
if (Array.isArray(current)) { | |
for (var i = current.length - 1; i >= 0; i--) { | |
queue.unshift(current[i]); | |
} | |
} else { | |
result.push(current); | |
} | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment