Created
September 17, 2022 13:09
-
-
Save mdpabel/66583926114adf879f97bd60a9d061b6 to your computer and use it in GitHub Desktop.
Infinite nexted array sum
This file contains hidden or 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
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