JSFiddle - React, Tailwind, and code Playground
HTML
<p>Elements for an average:
<span class="m">2</span>,
<span class="m">4</span>,
<span class="m">2</span>,
<span class="m">3</span>.
</p>
<p>r1. AVG "by .each()": <b id="r1"></b></p>
<p>r2. AVG "by .makeArray() and for": <b id="r2"></b></p>
<p>r3. AVG "by .makeArray() and reduce": <b id="r3"></b></p>
<p>r4. AVG "by .makeArray().map and reduce": <b id="r4"></b></p>
<p>r5. AVG "by .map().get() and reduce": <b id="r5"></b></p>
JavaScript
var tot = n = 0; // faster? http://jsperf.com/array-reduce-vs-jquery-each
$('.m').each(function(){
tot += parseInt( $(this).text() );
n++;
});
$('#r1').html(tot/n); // AVG1
var A = $.makeArray( $('.m') ); // how to map to innerHTML directly?
// faster than reduce, see http://jsperf.com/speedy-summer-upper
for(var i=0, Atot=0; i<A.length; i++)
Atot += parseInt(A[i].innerHTML);
var AVG2 = Atot/A.length;
$('#r2').html(AVG2);
// slower but really elegant...
var sum = A.reduce(function(previous, current) {
return parseInt(current.innerHTML) + previous;
},0);
var AVG3 = sum / A.length;
$('#r3').html(AVG3);
var A2 = $.makeArray( $('.m') ).map(function(a) {
return parseInt(a.innerHTML);
});
var sum2 = A2.reduce(function(a, b) {return a + b;});
var AVG4 = sum2 / A2.length;
$('#r4').html(AVG4);
var A5 = $('.m')
.map(function(idx) { return parseInt($(this).html()) })
.get();
var AVG5 = A5.reduce(function(a,b){return a+b}) / A5.length;
$('#r5').html(AVG5);