Skip to content

Instantly share code, notes, and snippets.

@ishandutta2007
Created April 8, 2019 16:03
Show Gist options
  • Save ishandutta2007/0d80c417b68ed835c31b1be7538f9c05 to your computer and use it in GitHub Desktop.
Save ishandutta2007/0d80c417b68ed835c31b1be7538f9c05 to your computer and use it in GitHub Desktop.
// flattenArray([[1,2,[3]],4]) // [1, 2, 3 , 4]
function flattenArray (input) {
if (Array.isArray(input)) {
return input.reduce(
function flattener (accumulator, value) {
if (Array.isArray(value)) {
return accumulator.concat(value.reduce(flattener, []))
} else {
return accumulator.concat(value)
}
}
,
[]
)
} else {
throw new TypeError('Argument must be an array')
}
}
// ES6 export
module.exports = exports.default = flattenArray
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment