In Javascript, if I have an array of arrays representing a matrix, say
x = [
[1,2,3,4],
[5,6,7,8],
[9,10,11,12]
];
summing it "horizontally" is easy and can be done like
x.map(function(y){
return y.reduce(function(a,b){
return a+b;
});
});
or
x.map(y => y.reduce((a, b) => a+b));
Now I would like to compute the "vertical" sum, which can be done
x.reduce(function(a, b){
return a.map(function(v,i){
return v+b[i];
});
});
or
x.reduce((a, b) => a.map((v,i) => v+b[i]));
But I am not happy with this version and I wish there were something nicer, more elegant and more straightforward. Maybe an easy way to transpose the matrix beforehand? anyone?
const x = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
];
const a = x.map((y) => y.reduce((a, b) => a + b));
const b = x.reduce((a, b) => a.map((v, i) => v + b[i]));
const c = x.flat().reduce((a , b) => a + b)
console.log('Summing horizontally: ' + JSON.stringify(a));
console.log('Summing vertically: ' + JSON.stringify(b));
console.log('Summing whole array: ' + JSON.stringify(c));
Note that I asked a similar question a few days ago (link) but that lacked the bigger picture.