Last active
January 20, 2020 22:53
-
-
Save MeyCry/ee1e47f4d0f0db3571a05d0e279a245d to your computer and use it in GitHub Desktop.
flatter for array
This file contains hidden or 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 flatter(arr) { | |
return arr.flat(Infinity); | |
} | |
flatter( | |
[1, 2, [3, 4, [5]], 6, [[7, [8]], 9]], | |
); | |
function flatter2(arr) { | |
const arrCopy = arr.slice(); | |
const result = []; | |
while (arrCopy.length) { | |
const next = arrCopy.pop(); | |
if (Array.isArray(next)) { | |
arrCopy.push(...next); | |
} else { | |
result.push(next); | |
} | |
} | |
return result.reverse(); | |
} | |
flatter2([1, 2, [3, 4, [5]], 6, [[7, [8]], 9]]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment