Skip to content

Instantly share code, notes, and snippets.

@toddbranch
Created December 9, 2015 20:35
Show Gist options
  • Save toddbranch/e4b77e2aef996ca13b59 to your computer and use it in GitHub Desktop.
Save toddbranch/e4b77e2aef996ca13b59 to your computer and use it in GitHub Desktop.
Flatten Array
// 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