Mark Guidone Mark Guidone - 16 days ago 5
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");
}
}

Answer

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]));

Comments