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.
I think you are unhappy that there is no native zip
function, because that's what your reduce
in the map
is essentially doing. You'll either have to implement it yourself or import it from a library like Ramda, in order to write elegant code like this:
var verticalSum = x.map(R.zipWith(function(a,b){ return a+b; }));
If you are looking for an efficient solution, there's basically no better way than explicit loops.