I have the following array:
myData = [[2, null, null, 12, 2],
[0, 0, 10, 1, null],
undefined];
I want to calculate the sum of each sub-matrix, so in my case, the result should be an array of the form: result = [16, 11, 0]. This means that nulland undefinedare replaced by zeros.
My approach works fine if I do not have the last item undefined:
MyCtrl.sum = MyCtrl.myData.reduce(function (r, a) {
a.forEach(function (b, i) {
r[i] = (r[i] || 0) + b;
});
return r;
}, []);
I tried several ways to return zero if there is nullor as a subband undefined, but I don't know how:
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;
}, []);
It says that "i" is not defined on the else branch.
Do you know any solution?