Skip to content

Instantly share code, notes, and snippets.

@nachogarcia
Created April 5, 2019 23:31
Show Gist options
  • Save nachogarcia/196f10351400f19a1cb94bad427725c4 to your computer and use it in GitHub Desktop.
Save nachogarcia/196f10351400f19a1cb94bad427725c4 to your computer and use it in GitHub Desktop.
Flatten in ES6
const unflattened = [[1,2,[3]],4]
const flattened = [1, 2, 3, 4]
// It would be much easier with the already provided in the language: const result = unflattened.flat(Infinity)
const flatten = arr => arr.reduce((flat, next) => flat.concat(Array.isArray(next) ? flatten(next) : next), [])
const result = flatten(unflattened)
expect(result).toEqual(flattened)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment