Skip to content

Instantly share code, notes, and snippets.

@marktellez
Created November 7, 2016 19:50
Show Gist options
  • Save marktellez/ea0795c881344391c6b95d33555a2f4b to your computer and use it in GitHub Desktop.
Save marktellez/ea0795c881344391c6b95d33555a2f4b to your computer and use it in GitHub Desktop.
Flattening an array is easy if you know recursion and map/reduce!
// I prefer NOT to monkey-patch, also you can't do lazy operations
// if we stick this on the array prototype!
function flatten (arr, depth=Infinity) {
if (depth === 0) return arr
return arr.reduce( (acc, v) => {
// normally I would ternary something like this, but the spread operator
// prevents it :)
if (Array.isArray(v)) {
acc.push(...flatten(v, depth-1))
} else {
acc.push(v)
}
return acc
}, [])
}
module.exports = flatten
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment