Skip to content

Instantly share code, notes, and snippets.

@david-j-davis
Created September 22, 2019 19:20
Show Gist options
  • Save david-j-davis/c56c8191654bdbe8d7a888330af64a1e to your computer and use it in GitHub Desktop.
Save david-j-davis/c56c8191654bdbe8d7a888330af64a1e to your computer and use it in GitHub Desktop.
Flatten an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4]
// Write some code, that will flatten an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4].
function flattenArray(arr) {
if (!Array.isArray(arr)) {
return 'Please enter an array'
}
return arr.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenArray(val)) : acc.concat(val), [])
}
// console.log(flattenArray(4)) // will return 'Please enter an array'
console.log(flattenArray([[1, 2, [3]], 4]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment