Skip to content

Instantly share code, notes, and snippets.

@michelarteta
Created November 1, 2018 20:16
Show Gist options
  • Save michelarteta/87130e389095730f9b78075e1da07917 to your computer and use it in GitHub Desktop.
Save michelarteta/87130e389095730f9b78075e1da07917 to your computer and use it in GitHub Desktop.
Flattering Array
// case [[1,2,[3]],4]
// case [[1, 2],[3, 4, 5], [6, 7, 8, 9]];
var array = [[1, 2],[3, 4, 5], [6, 7, 8, 9]];
function flattenArray(value) {
const stack = [...value];
const res = [];
while (stack.length) {
const next = stack.pop();
if (Array.isArray(next)) {
stack.push(...next);
} else {
res.push(next);
}
}
return res.reverse();
}
flattenArray(array);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment