Created
November 7, 2016 19:50
-
-
Save marktellez/ea0795c881344391c6b95d33555a2f4b to your computer and use it in GitHub Desktop.
Flattening an array is easy if you know recursion and map/reduce!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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