Skip to content
Home ยป JavaScript Tutorial Exercise 5: Calculating Average Student Grades in JavaScript Using reduce() and map()

JavaScript Tutorial Exercise 5: Calculating Average Student Grades in JavaScript Using reduce() and map()

function calculateAverageGrade(studentsArray) {
   let averageGrades=[];
   let studentGrades=[];
   let average = 0;
   let overallAverage = 0;
   for (let i=0; i <studentsArray.length; i++){
       studentGrades=studentsArray[i].grades;
       average = studentGrades.reduce((sum,grade) => sum + grade,0) / studentGrades.length;
       averageGrades.push(average);
    }
    overallAverage = averageGrades.reduce(
        (sum, grade) => sum + grade, 0
    ) / averageGrades.length;

    const surnames = studentsArray.map(
        student => student.surname
    );

    console.log(
        "Average grades for each student (" +
        surnames.join(",") + "): " +
        averageGrades.join(", ")
    );
    console.log("Overall average grade: " + overallAverage.toFixed(2));
}



function test(){
    const students = [
        {
            name: 'John',
            surname: 'Smith',            
            age: 16,
            index: '1',
            grades: [8,10,6,4]
        },
        {
            name: 'Jane',
            surname: 'Doe',            
            age: 16,
            index: '2',
            grades: [10,10,10,8]
        },
        {
            name: 'James',
            surname: 'Johnson',
            age: 17,
            index: '3',
            //grades: [6,6,4,4]
            grades: [3,3,2,2]
        }
    ];

    calculateAverageGrade(students);

}

JavaScript provides several powerful array methods that make it easier to process and analyze data. Two particularly useful methods are reduce() and map().

In this tutorial, we will create a JavaScript function that calculates the average grade for each student, determines the overall class average, and displays the results in the console.

The exercise demonstrates how to work with arrays of objects, nested arrays, arrow functions, and JavaScript’s built-in array methods.

1. Understanding the Student Data Structure

Our starting point is an array containing three student objects. Each student has a first name, surname, age, index, and an array of grades.

const students = [
    {
        name: 'John',
        surname: 'Smith',
        age: 16,
        index: '1',
        grades: [8, 10, 6, 4]
    },
    {
        name: 'Jane',
        surname: 'Doe',
        age: 16,
        index: '2',
        grades: [10, 10, 10, 8]
    },
    {
        name: 'James',
        surname: 'Johnson',
        age: 17,
        index: '3',
        grades: [3, 3, 2, 2]
    }
];

The students variable contains an array of objects. Each object represents one student, while the grades property contains another array holding that student’s grades.

This is an example of a nested data structure, where arrays are stored inside objects that are themselves elements of another array.

Our objective is to calculate three individual averages and one overall average.

2. Creating the calculateAverageGrade() Function

We begin by defining a function that accepts the array of students as its parameter.

function calculateAverageGrade(studentsArray) {
    let averageGrades = [];
    let studentGrades = [];
    let average = 0;
    let overallAverage = 0;
}

Four variables are initialized.

  1. averageGrades stores the calculated average for each student.
  2. studentGrades temporarily holds the grades of the student currently being processed.
  3. average stores the individual student’s calculated average.
  4. overallAverage stores the final average across all students.

The function is designed to process any number of students, provided each student has a valid, nonempty array of numeric grades.

3. Looping Through the Students

Next, we use a traditional for loop to iterate through the array.

for (let i = 0; i < studentsArray.length; i++) {
    studentGrades = studentsArray[i].grades;

    average = studentGrades.reduce(
        (sum, grade) => sum + grade, 0
    ) / studentGrades.length;

    averageGrades.push(average);
}

During each iteration, studentsArray[i] accesses the current student object.

The expression:

studentGrades = studentsArray[i].grades;

retrieves the student’s grades.

For John Smith, the resulting array is:

[8, 10, 6, 4]

We can now calculate the average of these four values.

4. Calculating the Average Using reduce()

One of the most interesting parts of this exercise is the use of the reduce() method.

studentGrades.reduce(
    (sum, grade) => sum + grade, 0
)

The reduce() method processes an array and combines its elements into a single accumulated result.

It accepts a callback function and, optionally, an initial accumulator value.

In our example:

  • sum represents the accumulated total.
  • grade represents the current grade being processed.
  • 0 is the initial value of the accumulator.
  • sum + grade adds the current grade to the accumulated total.

For John Smith, the operation proceeds as follows:

IterationGradeAccumulated sum
Initial0
188
21018
3624
4428

The final result of reduce() is 28.

To calculate the arithmetic average, we divide the sum by the number of grades.

average = studentGrades.reduce(
    (sum, grade) => sum + grade, 0
) / studentGrades.length;

For John Smith, this produces:

(8 + 10 + 6 + 4) / 4 = 7

The same calculation is repeated for Jane Doe and James Johnson.

Their averages are 9.5 and 2.5 respectively.

Why Use reduce() Instead of a Traditional Loop?

We could calculate the sum using another for loop, but reduce() expresses the accumulation operation more concisely.

It also eliminates the need to maintain a separate sum variable and can be reused for many other calculations, including totals, statistics, and data aggregation.

5. Storing the Individual Averages

Once an average has been calculated, it is added to the averageGrades array.

averageGrades.push(average);

The push() method appends a new element to the end of an array.

After processing all three students, the array contains:

[7, 9.5, 2.5]

The order of these averages corresponds to the order of the students in the original array.

6. Calculating the Overall Class Average

Now that we have the individual averages, we can calculate the overall class average.

overallAverage = averageGrades.reduce(
    (sum, grade) => sum + grade, 0
) / averageGrades.length;

Notice that we are using reduce() again, but this time on the array containing the individual averages.

The calculation is:

(7 + 9.5 + 2.5) / 3 = 6.333333...

The overall average is approximately 6.33.

An important detail is that this calculation gives every student equal weight, regardless of how many grades they have.

If some students had more grades than others, the average of all individual grades could differ from the average of the student averages.

In our example, each student has exactly four grades, so both approaches produce the same result.

7. Extracting Student Surnames Using map()

Another useful JavaScript array method is map().

We use it to extract the surnames from the student objects.

const surnames = studentsArray.map(
    student => student.surname
);

Unlike reduce(), which combines array elements into a single result, map() creates a new array by transforming each element of the original array.

For every student object, our arrow function returns the value of the surname property.

The resulting array is:

["Smith", "Doe", "Johnson"]

The original studentsArray remains unchanged.

This illustrates an important distinction between the two methods.

map() transforms an array into another array, while reduce() accumulates array elements into a result.

8. Formatting the Console Output Using join()

We now have two arrays.

const surnames = ["Smith", "Doe", "Johnson"];
const averageGrades = [7, 9.5, 2.5];

To display them in a readable format, we use the join() method.

surnames.join(",")

This produces:

Smith,Doe,Johnson

Similarly:

averageGrades.join(", ")

produces:

7, 9.5, 2.5

The difference is the separator passed to join(). The second example includes a space after each comma.

Finally, we combine the strings in a console.log() statement.

console.log(
    "Average grades for each student (" +
    surnames.join(",") + "): " +
    averageGrades.join(", ")
);

This displays the surnames alongside their corresponding averages.

9. Formatting the Overall Average Using toFixed()

The overall average contains a repeating decimal value.

To make the output more readable, we use toFixed(2).

console.log(
    "Overall average grade: " +
    overallAverage.toFixed(2)
);

The toFixed() method formats a number using a specified number of decimal places.

In this case, the result is:

6.33

One detail worth remembering is that toFixed() returns a string rather than a number.

This is perfectly suitable for displaying the result in the console.

10. Complete JavaScript Implementation

Here is the complete script, with the original calculation logic preserved.

function calculateAverageGrade(studentsArray) {
    let averageGrades = [];
    let studentGrades = [];
    let average = 0;
    let overallAverage = 0;

    for (let i = 0; i < studentsArray.length; i++) {
        studentGrades = studentsArray[i].grades;

        average = studentGrades.reduce(
            (sum, grade) => sum + grade, 0
        ) / studentGrades.length;

        averageGrades.push(average);
    }

    overallAverage = averageGrades.reduce(
        (sum, grade) => sum + grade, 0
    ) / averageGrades.length;

    const surnames = studentsArray.map(
        student => student.surname
    );

    console.log(
        "Average grades for each student (" +
        surnames.join(",") + "): " +
        averageGrades.join(", ")
    );

    console.log(
        "Overall average grade: " +
        overallAverage.toFixed(2)
    );
}

function test() {
    const students = [
        {
            name: 'John',
            surname: 'Smith',
            age: 16,
            index: '1',
            grades: [8, 10, 6, 4]
        },
        {
            name: 'Jane',
            surname: 'Doe',
            age: 16,
            index: '2',
            grades: [10, 10, 10, 8]
        },
        {
            name: 'James',
            surname: 'Johnson',
            age: 17,
            index: '3',
            grades: [3, 3, 2, 2]
        }
    ];

    calculateAverageGrade(students);
}

test();

Notice the additional test() call at the end. Defining a function does not execute it automatically. Calling test() starts the calculation.

Expected Console Output

Average grades for each student (Smith,Doe,Johnson): 7, 9.5, 2.5
Overall average grade: 6.33

11. Possible Improvements

Although the script works correctly with the provided data, several improvements could make it more robust and maintainable.

Handling Empty Arrays

If a student has no grades, dividing by studentGrades.length would result in division by zero.

Similarly, if the student array itself is empty, the overall average would become NaN.

A production implementation should explicitly handle these situations.

Using const Instead of let

Variables that are not reassigned can be declared using const.

For example, the individual grades array could be declared inside the loop.

const studentGrades = studentsArray[i].grades;

This limits the variable’s scope to the loop iteration and makes the code easier to maintain.

Returning Results Instead of Only Logging Them

Currently, the function displays the results but does not return them.

Returning a structured object would make the function more reusable.

For example, the calculated averages could be displayed on a webpage, exported to a file, or passed to another function.

Improving the Output

Instead of displaying two separate arrays, we could associate each student’s name directly with their average.

This would make the output clearer, particularly when working with a larger number of students.

12. Conclusion

This exercise demonstrates how several fundamental JavaScript concepts can work together to solve a practical data processing problem.

We used a traditional for loop to iterate through student objects, reduce() to calculate averages, push() to collect the results, map() to extract surnames, and join() to format arrays for console output.

We also used toFixed() to present the overall average with two decimal places.

The most important lesson is understanding the different responsibilities of JavaScript’s array methods.

reduce() is useful for aggregating data, while map() is designed for transforming data.

These techniques are not limited to student grades. They are equally useful when processing financial records, analyzing measurements, calculating performance statistics, or transforming API responses.

Mastering these methods provides a strong foundation for writing cleaner, more expressive JavaScript code.

Leave a Reply

Your email address will not be published. Required fields are marked *