Given a multi-dimensional array:
var a = [[3,2,5], [4,1,7], [1,6,8]];
I would like to do a cumulative sum of each array to return the following result:
[[3,2,5], [7,3,12], [8,9,20]];
- cum sum on 1st elements of each sub-array: 3 4 1
- cum sum on 2nd elements of each sub-array: 2 1 6
- cum sum on 3rd elements of each sub-array: 5 7 8
I've tried using reduce(), but can't quite get the expected result.
Any suggestions, much appreciated.
S
UPDATE - Taking it to the next level:
var a = [
[new Date(), 3,2,5],
[new Date(), null,1,7],
[new Date(), null,6,8],
[new Date(), 1,2,3]
];
Should result in:
[[new Date(), 3,2,5],
[new Date(), null,3,12],
[new Date(), null,9,20],
[new Date(), 4,11,23]]
My approach was to create a multi-dimensional offsetIndex array:
var offsetIdx = [];
for (var i=1; i<a.length; i++) {
for (var z=0; z<a[i].length; z++) {
var zValue = a[i][z];
oIdx = offsetIdx[z] || 0;
a[i][z] = zValue && z!==0 ? a[i-1-oIdx][z] + zValue : zValue;
if(!zValue){
offsetIdx[z] = oIdx + 1;
} else {
offsetIdx[z] = 0;
}
}
}
Happy to see other approaches and ways of making it ultra light-weight.