Created
January 30, 2018 04:27
-
-
Save bozdoz/929c63504d4e0858bbc44f9693a692df to your computer and use it in GitHub Desktop.
Recursively flattens 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
/** | |
* Recursively flattens nested arrays | |
* ex: [[1,2,[3]],4] -> [1,2,3,4] | |
* | |
* @param Array arr | |
* @return Array | |
*/ | |
const flatten = (arr) => ( | |
// reduce will iterate and | |
// add to an array | |
arr.reduce((a, b) => ( | |
// concat will join the inner | |
// arrays to the final array | |
a.concat(Array.isArray(b) ? flatten(b) : b) | |
), []) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment