Skip to content

Instantly share code, notes, and snippets.

@breadface
Last active May 30, 2016 20:00
Show Gist options
  • Save breadface/9cfb2391094a488af3f1f5f8c839b105 to your computer and use it in GitHub Desktop.
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
/*
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