Last active
November 10, 2016 08:15
-
-
Save hrehman200/887f3f9938f386b33bae63d53e282e87 to your computer and use it in GitHub Desktop.
Flattens an arbitrary nested arrays of integers
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
/** | |
* Flattens an arbitrary nested arrays of integers | |
* e.g. [[1,2,[3]],4] -> [1,2,3,4] | |
* | |
* @param arr The input array | |
* @param responseArr The output array we will be filling via recursion | |
* @returns {Array} The flattened array | |
*/ | |
function flattenArray(arr, responseArr) { | |
for(var i in arr) { | |
if(Array.isArray(arr[i])) { | |
flattenArray(arr[i], responseArr); | |
} else { | |
responseArr.push(arr[i]); | |
} | |
} | |
return responseArr; | |
} | |
console.log(flattenArray([[1,2,[3]],4], [])); | |
console.log(flattenArray([[[1,2,[3]],4]], [])); | |
console.log(flattenArray([[1],[2,3],[4,5,6]], [])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment