Skip to content

Instantly share code, notes, and snippets.

@simsketch
Created February 1, 2017 16:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simsketch/8315dc517c66036451c21021ad2a9848 to your computer and use it in GitHub Desktop.
Save simsketch/8315dc517c66036451c21021ad2a9848 to your computer and use it in GitHub Desktop.
Write some code, that will flatten an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4].
function flatten(array) {
var idx,
temp = [array],
lastIdx = [-1],
result = [];
while(temp.length) {
array = temp.pop();
idx = lastIdx.pop() + 1;
for(; idx < array.length; ++idx) {
if (Array.isArray(array[idx])) {
temp.push(array);
lastIdx.push(idx);
array = array[idx];
idx = -1;
} else {
result.push(array[idx]);
}
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment