Suppose we have an array of numbers like this:
var values = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
The average value is obtained by the following formula
A = (1 / n) Σxi (from i = 1 to n) ... So: x1 / n + x2 / n + ... + xn / n
We divide the current value by the number of values and add the previous result to the return value.
Signature Reduction Method
reduce(callback[,default_previous_value])
The callback function reduces the following parameters:
- p : Result of previous calculation
- c : current value (from current index)
- i : current array element index value
- a : current reduced array
The second reduction parameter is the default value ... (used if the array is empty ).
Thus, the average reduction method will be:
var avg = values.reduce(function(p,c,i,a){return p + (c/a.length)},0);
If you prefer, you can create a separate function
function average(p,c,i,a){return p + (c/a.length)}; function sum(p,c){return p + c)};
And then just refer to the callback method signature
var avg = values.reduce(average,0); var sum= values.reduce(sum,0);
Or skip the prototype array directly.
Array.prototype.sum = Array.prototype.sum || function (){ return this.reduce(function(p,c){return p+c},0); };
You can split the value each time you call the reduction method.
Array.prototype.avg = Array.prototype.avg || function () { return this.reduce(function(p,c,i,a){return p+(c/a.length)},0); };
Or even better , using the previously defined Array.protoype.sum ()
optimize the process causing division only once :)
Array.prototype.avg = Array.prototype.avg || function () { return this.sum()/this.length; };
Then to any object of the array area:
[2, 6].avg();
NB: an empty array with the return of the NaN wish is rather 0 in my point of view and can be useful in specific cases of use.