Created
January 29, 2019 15:10
-
-
Save nomadrat/cf835b238bac58b15e45dce258025667 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
function flatten(inputArray) { | |
/** | |
* One can argue that it's a good idea to validate inputArray | |
* value here, but i disagree. In this exact case it's better | |
* to not reinvent the wheel — if inputArray is not an Array | |
* application will throw error anyway at .reduce step | |
*/ | |
return inputArray.reduce((accumulator, current) => { | |
if (Array.isArray(current)) { | |
return [ | |
...accumulator, | |
...flatten(current) | |
]; | |
} else { | |
// can also be done via accumulator.concat(current) | |
return [ | |
...accumulator, | |
current | |
]; | |
} | |
}, []); | |
} | |
console.log(flatten([1,3,[5, [9,10, [11,22]]]])); | |
console.log(flatten([])); | |
console.log(flatten([1,3])); | |
console.log(flatten([1,3,[5, [9,10]]])); | |
console.log(flatten([89, [3, 5], 1, [[17, 11]]])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment