EN
JavaScript - compute sum and average of elements in array
0
points
In this article, we would like to show you how to compute the sum and average of elements in the array in JavaScript.
Practical example
In this example, we use reduce() method to calculate sum of array elements. Then we use the sum to calculate the average value.
// ONLINE-RUNNER:browser;
const array = [1, 2, 3];
const sum = array.reduce((a, b) => a + b, 0);
const average = sum / array.length || 0;
console.log(sum); // 6
console.log(average); // 2