views:

440

answers:

1

Is it possible to create a dynamic array using something like this and store X elements, then get the average? How would that be possible?

$(xml).find('student').each(function(){
    var name = $(this).find("name").text();
        var myArray = DYNAMIC ELEMENTS

    student_list.append("<tr><td>"+name+"</td><td>"+cid+"</td><td>"+grade+"</td></tr>");
});

I want to store a set of grades for each class, then get the average of ALL the elements in the array. I would need to get a count of all the elements for it has increasing "key:value" Correct?

Along these lines: myArray[1] = "54" = myArray[i] = g <- dynamic

Ryan

+2  A: 

Key/value is used with dictionary types, not arrays. To get the average you simply add up all of the elements in the array, then divide by the length of the array. You can get each element by for looping through it.

var allGrades = [];

$.each( ... // whatever you had over here ... function() {
     var grade = $(this).find("course").text();
     allGrades[allGrades.length] = Number(grade);
});

// Average grades
var gradesTotal = 0;
for (var i = 0; i < allGrades.length; i++) {
    gradesTotal += allGrades[i];
}

var gradesAverage = gradesTotal / allGrades.length;
T. Stone
`allGrades[allGrades.length] = Number(grade);` this could (and probably should) be shortened to `allGrades[] = Number(grade);`
Doug Neiner
Gonna try this out! Thank you
Coughlin