Skip to content

Instantly share code, notes, and snippets.

@MohdSaifulM
Created December 1, 2022 17:04
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 MohdSaifulM/c04972d9076f12f3132cd0c327ca3648 to your computer and use it in GitHub Desktop.
Save MohdSaifulM/c04972d9076f12f3132cd0c327ca3648 to your computer and use it in GitHub Desktop.
Algorithms - Recursion
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