Array Average Value
Join the Discussion
Finding the average value of the entries in an array is a little different from finding the maximum or minimum value in the array since an average only really makes sense when the entries in the array are numbers. Another difference from finding the maximum or minimum value is that the code required to loop through the array is not so obvious and would therefore be even harder to understand if created in your regular code. Adding a method to the built-in Array object to extract the average of any numerical values stored in the array is therefore a useful addition to that object.
First off we need to decide what we are going to do about array entries that are not numbers. Two alternatives would be to treat all non-numbers as zero which would move the average closer to zero when there are non-numbers in the array or we could simply ignore those entries and get the average of just those entries that are numbers. Where you have an array that consists entirely of numbers both of these would return exactly the same result. Where you have an array with mixed content you are unlikely to want to get an average value at all and so which we choose shouldn't make any significant difference. I am going to present the code necessary to get the average of any numerical values from the array such that any numerical text strings are converted to their numerical equivalent but where any other non-numerical values are completely ignored. This is probably the option that requires the most complex code since we need to take special note of those values that equate to zero when converted to a number so as to only count 0 and '0' in our averaging but in my opinion this would produce the most meaningful result if you ad a situation where you did need to find the average of the numbers in an array where there are some entries that are not numbers.
var av = 0;
var cnt = 0;
var len = this.length;
for (var i = 0; i < len; i++) {
var e = +this[i];
if(!e && this[i] !== 0 && this[i] !== '0') e--;
if (this[i] == e) {av += e; cnt++;}
}
return av/cnt;
}
With that code in place we can now call that method for any array in order to retrieve the average of the numerical values that the array contains. For example:
var average = ary.avg();
This code will set average to 5.714285714285714 which is the average of the seven numbers we have in that array.

