Created
January 27, 2019 23:01
-
-
Save Noitidart/ed39c15fcf863db89712be9a3bf384b4 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 flattenRecur(arr) { | |
// arr is either array or non-array | |
if (!Array.isArray(arr)) return arr; | |
const newArr = []; | |
for (const el of arr) { | |
const flattened = flattenRecur(el); | |
if (Array.isArray(flattened)) newArr.push(...flattened); | |
else newArr.push(flattened); | |
} | |
return newArr; | |
} | |
function flattenIter(arr) { | |
const newArr = []; | |
const queue = arr.slice(); | |
while (queue.length) { | |
const el = queue.shift(); | |
if (Array.isArray(el)) queue.unshift(...el); | |
else newArr.push(el); | |
} | |
return newArr; | |
} | |
console.log(flattenIter([ | |
1, | |
[2, 3], | |
4, | |
[5, [6, []], 7], | |
[[[[1]]]] | |
])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment