Created
September 18, 2019 14:54
-
-
Save lucasff/7aa85c05a1322973f5c7aa647cfadde9 to your computer and use it in GitHub Desktop.
JS flatten
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
const flatten = (arr, result = []) => { | |
if (!Array.isArray(arr)){ | |
return [...result, arr]; | |
} | |
arr.forEach((elem) => { | |
result = flatten(elem, result) | |
}) | |
return result | |
} | |
console.log(flatten([1, [2, 3], [4, [5, 6, [7, 8]]]])) // [ 1, 2, 3, 4, 5, 6, 7, 8 ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment