Last active
June 18, 2018 22:30
-
-
Save mattbontrager/d432defea5be59169ebc26b5e4709f59 to your computer and use it in GitHub Desktop.
Flatten arbitrarily nested arrays.
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 flatten(arr) { | |
return arr.reduce((flat, toFlatten) => { | |
return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten); | |
}, []); | |
} | |
// usage: | |
flatten([[1, 2, 3], [4, 5]]); // [1, 2, 3, 4, 5] | |
flatten([[[1, [1.1]], 2, 3], [4, 5]]); // [1, 1.1, 2, 3, 4, 5] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment