Created
February 2, 2018 13:45
-
-
Save rebelliard/b30ee2eedd33e2d35e9a8472a47b4b90 to your computer and use it in GitHub Desktop.
Flatten array
This file contains hidden or 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
/** | |
* Recursively flatten an array. | |
* @example | |
* input: [[1,2,[3]],4] | |
* output: [1,2,3,4] | |
**/ | |
function flatten(current) { | |
let accumulator = [] | |
if (Array.isArray(current)) { | |
// Process the nested array. | |
current.forEach(item => { | |
// Flatten this children and add it to the result. | |
accumulator = accumulator.concat(flatten(item)) | |
}) | |
} else { | |
// No need for further processing. | |
accumulator.push(current) | |
} | |
return accumulator | |
} | |
module.exports = flatten |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment