javascript applying function to different arrays

What i want to achieve:

  1. A function that calculates the average score of an array with scores.
  2. Make the function re-usable for different arrays

Achieved so-far:

const grades = [9, 8, 5, 7, 7, 4, 9, 8, 8, 3, 6, 8, 5, 6];
function classAverage () {
    let sumOfGrades = 0;
    for(let i = 0; i < (grades.length); i++) {
        sumOfGrades += grades[i];

    }
    const averageGrade = sumOfGrades/(grades.length);
    return averageGrade;
}
classAverage(grades);
console.log(averageGrade);

This seem to work in my ide, here it produces an error averageGrade not defined. Next i’d like this function to be apply-able to more arrays like grades1999 or grades2021 but the for loop inside the function uses the grades array for calculation, how can i achieve that this function would work with something like: classAverage grades(2019) arrays with different names.

Thank you for your time!

Answer

You can add a method (classAverage) to the Array.prototype and then call it with different grade arrays.

Array.prototype.classAverage = function () {
  return this.reduce((r, g) => r + g, 0) / (this.length || 1);
};

const grades = [9, 8, 5, 7, 7, 4, 9, 8, 8, 3, 6, 8, 5, 6];
const grades1999 = [1, 8, 3, 5, 7, 2, 4, 3];
const grades2020 = [5, 6, 7, 8, 2, 3, 4, 5, 6, 7, 8];
const grades2023 = [];

console.log(grades.classAverage());
console.log(grades1999.classAverage());
console.log(grades2020.classAverage());
console.log(grades2023.classAverage());