Last active
February 12, 2019 17:01
-
-
Save Noitidart/a31723bfeccc78b5822c166078f114b3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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