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.
In this example, we use reduce()
method to calculate sum
of array
elements. Then we use the sum
to calculate the average
value.
xxxxxxxxxx
1
const array = [1, 2, 3];
2
3
const sum = array.reduce((a, b) => a + b, 0);
4
const average = sum / array.length || 0;
5
6
console.log(sum); // 6
7
console.log(average); // 2