JavaScript Program to Calculate the Average of All the Elements Present in an Array
Given an array “arr” of size N, the task is to calculate the average of all the elements of the given array.
Example:
Input: arr = {1, 2, 3, 4, 5}
Output: 3
Explanation: (1+2+3+4+5) / 5 = 15/5 = 3
These are the following approaches:
Table of Content
- Using for loop
- Using a while loop
- Using reduce() method
- Using forEach method
Using for loop
This JavaScript program defines a function to calculate the average of elements in an array. It iterates through each element, sums them up, and divides the total by the number of elements. Finally, it returns the average value.
Example: This example shows the implementation of the above-explained approach.
function calAvg(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum / arr.length;
}
const arr = [10, 20, 30, 40, 50];
const average = calAvg(arr);
console.log("Average:", average);
Output
Average: 30
Using a while loop
Here we define a function to calculate the average of elements in an array using a while loop. It initializes a sum variable, iterates through each element with an index variable, updates the sum, and finally divides it by the array length to compute the average.
Example: This example shows the implementation of the above-explained approach.
function calculateAverage(arr) {
let sum = 0;
let i = 0;
while (i < arr.length) {
sum += arr[i];
i++;
}
return sum / arr.length;
}
const arr = [10, 20, 30, 40, 50];
const average = calculateAverage(arr);
console.log("Average:", average);
Output
Average: 30
Using reduce() method
The approach sums array elements with reduce(), divides by array length for average. Utilizes reduce’s accumulator to compute total sum, then divides by array length to derive average value.
Example: This example shows the implementation of the above-explained approach.
let array = [10, 22, 16, 24];
let sum = array.reduce((acc, curr) => acc + curr, 0);
let average = sum / array.length;
console.log("Average: "+average);
Output
Average: 18
Using forEach method
This method uses the forEach method to iterate over the array and sum the elements. Then we calculate the average by dividing the sum by the number of elements in the array.
Example: This example shows the implementation of the above-explained approach.
function calculateAverage(array) {
let sum = 0;
array.forEach(function(element) {
sum += element;
});
return sum / array.length;
}
let numbers = [1, 2, 3, 4, 5];
console.log("Average: "+calculateAverage(numbers));
Output
Average: 3