Last active
April 24, 2019 22:04
-
-
Save adrianbona/3302bb0161cc4eaa6bbf695ead298a13 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
/** | |
* Flattens an array. | |
* | |
* Flattens an array of arbitrarily nested arrays of integers into a flat array of integers. | |
* | |
* @param {array} myArray Array to be flattened. | |
* | |
* @return {array} Flattened version of input array. | |
*/ | |
function flattenMyArray(myArray) { | |
let result = []; | |
for (let i = 0; i < myArray.length; i++) { | |
if (Array.isArray(myArray[i])) { | |
result = result.concat(flattenMyArray(myArray[i])); | |
} else { | |
result.push(myArray[i]); | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment