Calculate the sum of array elements, which can be zero or undefined

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?

+4
source share
3 answers

, , , .

.

var array = [[2, null, null, 12, 2], [0, 0, 10, 1, null], undefined],
    result = array.map(a => (a || []).reduce((s, v) => s + (v || 0), 0));
    
console.log(result);
+8

( lodash):

var myData = [[2, null, null, 12, 2],
          [0, 0, 10, 1, null],
           undefined];
// Flatten array
var myDataMerged = _.filter([].concat.apply([], myData), (v) => {
    return _.isNumber(v);
});

var sum = myDataMerged.reduce((a,b) => {
        return a+b;
});
console.log(myDataMerged);
console.log(sum);
+1

How about using .map?

var myData = [
    [2,null,null,12,2],
    [0,0,10,1,null],
    undefined
];

var sum = myData.map(function(item,index){
    if(!item)return 0;
    if(item.length <2)return item[0];
    return item.reduce(function(i1,i2){return i1+i2});
});;


console.log(sum);//[ 16, 11, 0 ]
+1
source

Source: https://habr.com/ru/post/1693062/


All Articles