Skip to content

Instantly share code, notes, and snippets.

@rebelliard
Created February 2, 2018 13:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rebelliard/b30ee2eedd33e2d35e9a8472a47b4b90 to your computer and use it in GitHub Desktop.
Save rebelliard/b30ee2eedd33e2d35e9a8472a47b4b90 to your computer and use it in GitHub Desktop.
Flatten array
/**
* 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