If you want to get the average of the elements in a
and b
, you need to be summing those elements, not the elements of first
.
Also, you had an extra ;
after if (avg1 > avg2)
, which was creating an empty body for that conditional, so return "first"
was being executed unconditionally.
function compare(a,b) {
var sum = 0;
for(var i=0; i<a.length;i++) {
sum += a[i];
var avg1 = (sum/a.length);
}
var sum2 = 0;
for(i=0;i<b.length;i++) {
sum2 += b[i];
var avg2 = (sum2/b.length);
}
if (avg1 > avg2) {
return "first";
} else {
return "second";
}
}
alert(compare([80, 100], [100, 100]));
alert(compare([100, 150, 200], [50, 75, 100, 110]));
2
solved find the average of both arrays, and then spit out the greater of the two