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?
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With