0

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

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

2 Comments

allGrades[allGrades.length] = Number(grade); this could (and probably should) be shortened to allGrades[] = Number(grade);
Gonna try this out! Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.