Skip to content

Instantly share code, notes, and snippets.

@farhatnawaz
Created June 21, 2017 19:26
Show Gist options
  • Save farhatnawaz/31d7f0f3b3b8753b4fe5ffff6b8fc919 to your computer and use it in GitHub Desktop.
Save farhatnawaz/31d7f0f3b3b8753b4fe5ffff6b8fc919 to your computer and use it in GitHub Desktop.
This piece of code flattens the nested arrays
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