Created
October 24, 2016 20:33
-
-
Save funkjunky/e24490511641d9fe4d355be96d387880 to your computer and use it in GitHub Desktop.
Flatten's an array any level deep. (for Citrus Byte) [written in ES6 JS]
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
//Mutable version | |
const flatten = (arr) => | |
arr.reduce((c, v) => | |
(Array.isArray(v)) | |
? c.concat(flatten(v)) | |
: [...c, v] | |
, []); | |
//or more effecient, in place | |
const flatten_in = (arr) => | |
arr.reduce((c, v) => { | |
(Array.isArray(v)) | |
? c.push(...flatten(v)) | |
: c.push(v) | |
return c; | |
}, []); | |
console.log(flatten([[1,2,[3]],4])); | |
export default flatten; | |
export flatten_in; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment