JavaScript: Computing the average of an array after mapping each element to a value

Computing the average of an array after mapping each element to a value in JavaScript can be done using several approaches including the forEach() loop, parseInt() method, reduce() method, and for...of loop. This article demonstrates how to calculate the average by summing all array elements and dividing by the array length.

Given below are examples of arrays where we compute the average by summing values and dividing by the number of elements:

Input: [1, 2, 3, 4, 5]
Result: 3
Explanation: (1+2+3+4+5)/5 = 3

Input: [2, 4, 7, 9, 1, 3, 8]
Result: 4.857142857142857
Explanation: (2+4+7+9+1+3+8)/7 = 4.857142857142857

Table of Content

Using forEach() loop

The forEach() method iterates through each array element, allowing us to accumulate the sum:

  • Iterate over array elements using forEach()
  • Add each element to a running sum
  • Divide the total sum by array length

Example

let arr = [1, 2, 3, 4, 5];

// Computing the average using forEach
function calculateAverage(arr) {
    let sum = 0;
    
    // Iterate over the elements of the array
    arr.forEach(function(item) {
        sum += item;
    });
    
    // Return the average
    return sum / arr.length;
}

console.log("Average of all numbers is: " + calculateAverage(arr));
Average of all numbers is: 3

Using for loop with parseInt() method

This approach uses parseInt() to ensure proper number conversion, especially useful when dealing with string arrays:

  • Iterate using a for loop
  • Use parseInt() to parse elements as numbers
  • Accumulate the sum and calculate average

Example

let arr = ["2", "4", "7", "9", "1", "3", "8"];
let sum = 0;

// Iterating elements using for loop
for (let i = 0; i < arr.length; i++) {
    // Parse each element as integer and add to sum
    sum += parseInt(arr[i], 10);
}

// Calculate the average
let avg = sum / arr.length;
console.log("Average is: " + avg);
Average is: 4.857142857142857

Using reduce() method

The reduce() method provides a concise way to sum array elements:

  • Use reduce() to accumulate the sum in one operation
  • The callback function adds current element to the accumulator
  • Divide the result by array length for average

Example

let arr = [4, 8, 12, 16];

// Using reduce to calculate the sum
let sum = arr.reduce((accumulator, current) => accumulator + current, 0);

// Calculate the average
let avg = sum / arr.length;

console.log("Average is: " + avg);
Average is: 10

Using for...of Loop

The for...of loop provides clean syntax for iterating array values:

  • Initialize a total variable to store the sum
  • Use for...of to iterate through each array element
  • Add each value to the total
  • Calculate average by dividing total by array length

Example

let arr = [10, 15, 20, 25, 30];

// Function to calculate average using for...of loop
function calculateAverage(array) {
    let total = 0;
    
    // Iterate over array elements
    for (let num of array) {
        total += num;
    }
    
    // Return the average
    return total / array.length;
}

console.log("The average is: " + calculateAverage(arr));
The average is: 20

Comparison of Methods

Method Best For Readability Performance
forEach() General use Good Good
for with parseInt() String arrays Moderate Good
reduce() Functional programming Excellent Good
for...of Simple iteration Excellent Best

Conclusion

All four methods effectively calculate array averages, with reduce() and for...of offering the most readable solutions. Choose based on your specific needs: use parseInt() for string arrays, reduce() for functional style, or for...of for optimal performance.

Updated on: 2026-03-15T23:19:00+05:30

991 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements