user39980
user39980

Reputation:

Create dynamic array from each in jquery?

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

Upvotes: 0

Views: 3775

Answers (1)

T. Stone
T. Stone

Reputation: 19485

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;

Upvotes: 1

Related Questions