Created
December 1, 2022 17:04
-
-
Save MohdSaifulM/c04972d9076f12f3132cd0c327ca3648 to your computer and use it in GitHub Desktop.
Algorithms - Recursion
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
function flatten(arr) { | |
let result = []; | |
// Iterate through elements in array | |
for (let i = 0; i < arr.length; i++) { | |
// Check if element is array | |
if (Array.isArray(arr[i])) { | |
// Recursive case - concat result with recursive function | |
result = result.concat(flatten(arr[i])); | |
} else { | |
// If number push into result | |
result.push(arr[i]); | |
} | |
} | |
return result; | |
} | |
// flatten([1, 2, 3, [4, 5] ]) // [1, 2, 3, 4, 5] | |
// flatten([1, [2, [3, 4], [[5]]]]) // [1, 2, 3, 4, 5] | |
// flatten([[1],[2],[3]]) // [1,2,3] | |
// flatten([[[[1], [[[2]]], [[[[[[[3]]]]]]]]]]) // [1,2,3] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment