In this scenario, I have an array that looks like this:
myData = [[2, null, null, 12, 2],
[0, 0, 10, 1, null],
undefined];
The goal is to calculate the sum of each sub-array, resulting in an array like this: result = [16, 11, 0]
. The idea is to replace both null
and undefined
with zeros.
My current method works well excluding the case where the last element is undefined
:
MyCtrl.sum = MyCtrl.myData.reduce(function (r, a) {
a.forEach(function (b, i) {
r[i] = (r[i] || 0) + b;
});
return r;
}, []);
I attempted different approaches to handle the substitution of zero for null
or undefined
within a sub-array but encountered difficulty:
MyCtrl.sum = MyCtrl.myData.reduce(function (r, a) {
if(a) {
a.forEach(function (b, i) {
r[i] = (r[i] || 0) + b;
}); } else {
r[i] = 0;
}
return r;
}, []);
An issue arises stating that 'i' is not defined in the else statement.
If you have any suggestions or solutions to this problem, please share your insights.