Skip to content

Instantly share code, notes, and snippets.

@CarlLee
Created October 16, 2018 08:16
Show Gist options
  • Save CarlLee/d603fece1de554dba008f872378dedd4 to your computer and use it in GitHub Desktop.
Save CarlLee/d603fece1de554dba008f872378dedd4 to your computer and use it in GitHub Desktop.
An answer to a programming test from CitrusByte in Javascript.
/*
* Flattens a nested array into a one-dimentional array of the exact same order
*
* @param {Array} arr
* @return {Array} result
*/
function flattenArray(arr) {
// Internal function to flatten the input array recursively
function flattenArrayRecursively(arr, result) {
for(let i = 0; i < arr.length; i++) {
let element = arr[i];
if(Array.isArray(element)){
flattenArrayRecursively(element, result);
} else {
result.push(element);
}
}
}
let result = [];
flattenArrayRecursively(arr, result);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment