The challenge you are facing is due to the fact that your array contains not only arrays but also single numbers and nested arrays. This causes an issue where your inner loop cannot iterate over the number 4
because it is not an array (and therefore does not have a .length
property).
let arr = [[1,2],4];
// no issues-^ ^-- no `.length` property (inner for loop won't run)
To solve this problem, you can utilize a recursive function. When encountering a nested array, you can recursively call your function to calculate the sum for that specific array.
Here's an example along with code comments:
function sumNums(arr) {
let total = 0;
for (let i = 0; i < arr.length; i++) {
if(Array.isArray(arr[i])) {
total += sumNums(arr[i]);
} else {
total += arr[i];
}
}
return total;
}
let arr = [[1,2],4];
console.log(sumNums(arr)); // 7
You can also achieve the same result using a recursive call with .reduce()
:
const arr = [[1,2],4];
const result = arr.reduce(function sum(acc, v) {
return acc + (Array.isArray(v) ? v.reduce(sum, 0) : v);
}, 0);
console.log(result); // 7