How would I go about calculating the average of all the values in a multidimensional array? I've written a function to calculate the average from a 1-dimensional array, but I'm not sure what the best method is when there are more than 1-dimensions.
For example, let's say we have the following:
var A = Array(3);
for (i=0; i<A.length; i++) {
A[i] = new Array(2);
for (j=0; j<A[i].length; j++) {
A[i][j] = i+j;
}
}
Therefore, A is a 2-dimensional array, or 3x2 matrix:
A = 0 1
1 2
2 3
So I'd like to find the average of all the values, which in this case would equal 1.5. I imagine I need to create a new 1-dimensional array of all the values, which I could then feed into my averaging function. However, I'm not sure of the easiest way to do this when the array is highly-dimensional (e.g. 5x3x6x9).
Thanks!
EDIT
Thanks everyone! I've used your advice and flattened the array using code I found in one of the attached links which uses the reduce function. My averaging function is now like this:
function average(x) {
// Flatten multi-dimensional array
while (x[0] instanceof Array) {
x = x.reduce( function(a, b) { return a.concat(b); } );
}
// Calculate average
return x.reduce( function(a, b) { return a + b; } )/x.length;
}