Skip to content

Instantly share code, notes, and snippets.

@gpDA
Created February 23, 2022 18:33
Show Gist options
  • Save gpDA/69206c1df3e12f728dd773c979d115b4 to your computer and use it in GitHub Desktop.
Save gpDA/69206c1df3e12f728dd773c979d115b4 to your computer and use it in GitHub Desktop.
function flatten(arr, ret = []) {
for (const entry of arr) {
if (Array.isArray(entry)) {
flatten(entry, ret)
} else {
ret.push(entry)
}
}
return ret;
}
const arr1 = [0, 1, 2, [3, 4]];
const arr2 = [1, 2, [3, 4, 5, [6, 7]]];
console.log(flatten(arr1)); // [ 0, 1, 2, 3, 4 ]
console.log(flatten(arr2)); // [1, 2, 3, 4, 5, 6, 7]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment