Skip to content

Instantly share code, notes, and snippets.

@zakfisher
Created September 21, 2016 19:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zakfisher/31c41ca754fec3d56cd3f370ccb183c2 to your computer and use it in GitHub Desktop.
Save zakfisher/31c41ca754fec3d56cd3f370ccb183c2 to your computer and use it in GitHub Desktop.
// Create our array-flattening method (using a recursive approach)
const flatten = (arr) => {
// Return a new flattened array
return arr.reduce((prev, next) => {
// Make sure we have an array to add items to
prev = Array.isArray(prev) ? prev : [prev]
// If the next element in `arr` is not an array, add it to our flattened array
// Otherwise, pass the child array to this method, to be flattened recursively
return prev.concat(Array.isArray(next) ? flatten(next) : next)
})
}
// Try it out!
const x = [1, [2, 3], [[4], 5, 6]]
const y = flatten(x) // [1, 2, 3, 4, 5, 6]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment