Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compute the sum of elements of an array which can be null or undefined

I have the following array:

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

I want to compute the sum of each sub-array, so in my case the result should be an array of this form: result = [16, 11, 0]. This means that null and undefined to be replaced by zeros.

My approach works fine if I don't have the last element, undefined:

MyCtrl.sum = MyCtrl.myData.reduce(function (r, a) {
    a.forEach(function (b, i) {
        r[i] = (r[i] || 0) + b;
    }); 
    return r;
}, []);

I tried some ways to return zero if there is a null or undefined as a sub-array 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 to this?

like image 921
Leo Messi Avatar asked Dec 24 '22 10:12

Leo Messi


2 Answers

You could map the values by checking the inner array and if it is not given, then take an array as default value.

For adding, you could use zero as default value in a reduce with zero as start value.

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);
like image 171
Nina Scholz Avatar answered Feb 10 '23 08:02

Nina Scholz


You can try (using 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);
like image 35
Terry Lennox Avatar answered Feb 10 '23 08:02

Terry Lennox