Skip to content

Instantly share code, notes, and snippets.

@hrehman200
Last active November 10, 2016 08:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hrehman200/887f3f9938f386b33bae63d53e282e87 to your computer and use it in GitHub Desktop.
Save hrehman200/887f3f9938f386b33bae63d53e282e87 to your computer and use it in GitHub Desktop.
Flattens an arbitrary nested arrays of integers
/**
* 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