Skip to content

Instantly share code, notes, and snippets.

@tpgmartin
Created May 2, 2017 01:39
Show Gist options
  • Save tpgmartin/3a027d86ab80ef22e0568f81e65f5b8d to your computer and use it in GitHub Desktop.
Save tpgmartin/3a027d86ab80ef22e0568f81e65f5b8d to your computer and use it in GitHub Desktop.
Flatten array sample assuming input will only ever contain nested arrays of numbers
function flatten(arr, flat) {
let output = !!flat ? flat : []
arr.forEach((el) => {
if (typeof el === 'number') {
output.push(el)
} else {
flatten(el, output)
}
})
return output
}
flatten([1, 2, [3, [4], 5, 6], 7]) // [1, 2, 3, 4, 5, 6, 7]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment