Skip to content

Instantly share code, notes, and snippets.

@dstreet
Created October 18, 2017 17:54
Show Gist options
  • Save dstreet/cb1915a67c44f4e23a2292a82882842a to your computer and use it in GitHub Desktop.
Save dstreet/cb1915a67c44f4e23a2292a82882842a to your computer and use it in GitHub Desktop.
Flatten a JS array
const assert = require('assert')
const flatten = arr => arr.reduce((acc, el) => {
return acc.concat(Array.isArray(el) ? flatten(el) : el)
}, [])
assert.deepEqual(flatten([1, 2, 3, 4]), [1, 2, 3, 4])
assert.deepEqual(flatten([1, [2, 3], 4]), [1, 2, 3, 4])
assert.deepEqual(flatten([1, [2, [3]], 4]), [1, 2, 3, 4])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment