Last active
May 30, 2016 20:00
-
-
Save breadface/9cfb2391094a488af3f1f5f8c839b105 to your computer and use it in GitHub Desktop.
A function that reduces a list of multiple nested list to a single list containing all its values
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
/* | |
recursive calls to flatten will append items of inner array to the accumulator | |
e.g flatten :: [[1,2,[3]],4] -> [1,2,3,4] | |
*/ | |
const flatten = list => { | |
if (!Array.isArray(list)) | |
throw new Error(`Expecting input of type Array but found ${typeof list}`) | |
return list.reduce((accumulator, item) => | |
accumulator.concat(Array.isArray(item) ? flatten(item) : item), | |
[]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment