Skip to content

Instantly share code, notes, and snippets.

@Noitidart
Last active February 12, 2019 17: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 Noitidart/a31723bfeccc78b5822c166078f114b3 to your computer and use it in GitHub Desktop.
Save Noitidart/a31723bfeccc78b5822c166078f114b3 to your computer and use it in GitHub Desktop.
function flattenArrayRecursive(arr) {
if (!Array.isArray(arr)) return [arr];
const res = [];
for (const el of arr) {
res.push(...flattenArrayRecursive(el));
}
return res;
}
function flattenArrayIterative(els) {
const res = [];
// modified queue, intead of push, unshift, to maintain origianl els order
const queue = [els];
while (queue.length) {
const el = queue.shift();
if (Array.isArray(el)) queue.unshift(...el);
else res.push(el);
}
return res;
}
console.log(flattenArrayRecursive([1]));
console.log(flattenArrayIterative([1]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment