This post will illustrate the methods for computing the sum and the average of the array elements.
How to Compute/Calculate the Sum and Average of Elements in an Array?
To compute the sum and the average of the elements of an array, use the following approaches:
Method 1: Compute the Sum and Average of Elements in an Array Using “reduce()” Method
To compute the sum and average of the array elements, use the “reduce()” method. It uses the callback function that applies to every element of an array and gives a single reduced output. This method accepts two parameters a callback function and an optional initial value.
Syntax
Use the given-provided syntax for the reduce() method:
// statement
}, initialValue)
Example
Create an array of the first 10 even numbers:
Call the “reduce()” method with array to get the sum of all the array elements and store it in a variable “sum”:
Now, divide the sum with the length of an array to get the average of the array elements:
Print the result “sum” and the “average” on the console:
console.log("Average of Array Elements: " + average);
The output displays the sum of first 10 even numbers that is “110” and the average is “11”:
Method 2: Compute the Sum and Average of Elements in an Array Using “for-of” Loop
Another way to calculate the sum and average of the array elements is the traditional loops, such as for loop, while loop, for-of loop and so on. Here, we will discuss the “for-of” loop for computing the sum and the average of the array elements.
Syntax
The following syntax is utilized for the for-of loop:
//statement
}
Example
Create a variable “sum” and assign a value 0 to it:
Use the for-of loop and add the sum of the elements in the variable “sum”:
sum += x;
}
For calculating an average of array elements, divide the sum of the elements with the length of the array:
Finally, print the result on the console:
console.log("Average of Array Elements: " + average);
Output
That’s all about the computing of sum and the average of the array elements.
Conclusion
For calculating the sum and the average of the array, use the “reduce()” method or the loops, such as the “for” loop, “while” loop, or the “for-of” loop. However, the “reduce()” method is the most commonly used method for computing the sum and average of the array elements. This post will illustrate the methods for computing the sum and the average of the array elements.