Skip to content

Instantly share code, notes, and snippets.

@mdpabel
Created September 17, 2022 13:09
Show Gist options
  • Save mdpabel/66583926114adf879f97bd60a9d061b6 to your computer and use it in GitHub Desktop.
Save mdpabel/66583926114adf879f97bd60a9d061b6 to your computer and use it in GitHub Desktop.
Infinite nexted array sum
const arr = [
1,
[2],
[[3]],
[[[4]]],
[5],
[[[[[[[[[[[[7]]]]]]]], 1]]]],
7,
[[[10], [[[[[[[[1]]]]]]]]]],
];
function arraySum(arr) {
sum = 0;
for (const item of arr) {
if (Array.isArray(item)) {
sum += arraySum(item);
} else {
sum += item;
}
}
return sum;
}
res = arraySum(arr);
console.log(res);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment