Created
March 5, 2019 00:30
-
-
Save manduks/28e30f09dc11760d31e819917a258fa0 to your computer and use it in GitHub Desktop.
flatten an array of arbitrarily nested arrays of integers into a flat array of integers.
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
/** | |
* 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]. | |
**/ | |
const isInteger = (n) => { | |
if(Number.isInteger(n)) { | |
return n; | |
}; | |
throw "An item inside the array is not integer"; | |
} | |
let flatten = list => { | |
if (!Array.isArray(list)) { | |
throw "Not an array"; | |
} | |
return list.reduce( | |
(a, b) => a.concat(Array.isArray(b) ? flatten(b) : isInteger(b)), [] | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment