I have an array that looks like this:
var array = [ [1,3,9],
[4,6,8],
[3,7,5],
[2,8,4] ];
I want to get the average number of each column, but for now I was just trying to sum them. This is my code:
var sum = function(arr) {
return arr.reduce(function(a, b) { return a + b; }, 0);
};
var tests = array.map(function(v, i) {
return sum(array.map(function(v) { return v[i]; }))
});
return tests;
The output turns the sum correctly, but it seems to be doing as many sums as there are rows (4 rows), instead of 3 corresponding to the columns. This is the output:
tests = [10, 24, 26, NULL]
Any idea why is this happening? How can I perform the calculation only for as many columns as there are instead of rows?
EDIT:
I'm using Nenad's answer which gives the correct result. But I need to implement it on Google Sheets's Script Editor, which doesn't seem to understand the shortened functions with "=>". I replaced the shortened pieces for the longer version, but I'm not getting the same result.
var array = [ [1,3,9],
[4,6,8],
[3,7,5],
[2,8,4] ];
var sums = array.reduce(function(r, e, i) {
e.forEach(function(a,j) { r[j] = (r[j] || 0) + a;
if (i == array.length-1) { r = r.map(function(el){ return el/array.length; }); }
});
return r;
}, [])
console.log(sums);
I don't see any difference between this and the shortened version, yet this one returns:
sums = [0.15625, 0.75, 1.34375];
Instead of:
sums = [2.5, 6, 6.5];
The sum is done correctly, but when I divide "el/array.length" or even "el/4", the result are these 3 weird numbers. I don't understand where are those coming from. Where did I go wrong?