Created
September 22, 2019 19:20
-
-
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]
This file contains 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
// 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