function twoDSum(arr){
debugger
result = 0
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
result += twoDSum(arr[i])
} else {
result += arr[i]
}
}
return result
}
array_1 = [
[4, 5],
[1, 3, 7, 1]
]
console.log(twoDSum(array_1))
The code above works perfectly. However, my question is why the code below will produce the wrong answer. I assume I am computing the sum of the sub-array and store it into a variable and add it to my result instead, it is doubling on every single array
function twoDSum(arr){
debugger
result = 0
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
let subSum = twoDSum(arr[i])
result += subSum
} else {
result += arr[i]
}
}
return result
}
array_1 = [
[4, 5],
[1, 3, 7, 1]
]
console.log(twoDSum(array_1))