Mark Guidone - 1 year ago 83
Javascript Question

# find the average of both arrays, and then spit out the greater of the two

Whenever i run this it gives me, "first" instead of "second". Is my logic correct here? finding both avarages and then returning the greater? or what exactly do you see wrong with it.

``````var first = ([100, 80], [100, 100]);
function compare(a, b) {
sum = 0;
for(var i = 0; i < a.length; i++) {
sum += first[i];
avg1 = (sum/a.length);
}

sum2 = 0;
for(i = 0; i < b.length; i++) {
sum2 += first[i];
avg2 = (sum2/b.length);
}
if (avg1 > avg2); {
return ("first");
}
if (false) {
return ("second");
}
}
``````

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";
}
}