How to Compute the Sum and Average of Elements in an Array in JavaScript?
Computing the sum and average of elements in an array involves iterating through the array, accumulating the sum of its elements, and then dividing the sum by the total number of elements to get the average. This can be achieved using various techniques, from basic loops to more advanced functional methods provided by JavaScript.
These are the following approaches to computing the sum and average of elements in an array:
Table of Content
Using a for Loop
The simplest way to compute the sum and average is by using a basic for loop to iterate through the array, adding up each element's value to a sum variable, and then dividing by the length of the array to find the average.
Example: This example shows the use of for loop to get the sum and average of an array.
const array = [10, 20, 30, 40, 50];
let sum = 0;
for (let i = 0; i < array.length; i++) {
sum += array[i]; // Add each element to sum
}
let average = sum / array.length;
console.log("Sum:", sum);
console.log("Average:", average);
Output
Sum: 150 Average: 30
Using reduce() Method
The reduce() method executes a reducer function on each element of the array, resulting in a single output value. It's ideal for summing up array values.
Example: This example shows the use of reduce method to get the sum and average of an array.
const array = [10, 20, 30, 40, 50];
const sum =
array.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
const average = sum / array.length;
console.log("Sum:", sum);
console.log("Average:", average);
Output
Sum: 150 Average: 30
Using forEach() Method
The forEach() method executes a provided function once for each array element. You can use it to calculate the sum and then compute the average.
Example: This example shows the use of forEach() method to get the sum and average of an array.
const array = [10, 20, 30, 40, 50];
let sum = 0;
array.forEach((element) => {
sum += element; // Accumulate sum
});
const average = sum / array.length;
console.log("Sum:", sum);
console.log("Average:", average);
Output
Sum: 150 Average: 30
Using map() and reduce() Methods
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array. You can chain map() with reduce() to get the sum and compute the average.
Example: This example shows the use of map() and reduce() methods to get the sum and average of an array.
const array = [10, 20, 30, 40, 50];
const sum = array.map((element) => element).reduce((acc, curr) => acc + curr, 0);
const average = sum / array.length;
console.log("Sum:", sum);
console.log("Average:", average);
Output
Sum: 150 Average: 30