To compute the sum and average of elements in an array with JavaScript, we use the reduce
method.
For instance, we write
const average = (arr) => arr.reduce((p, c) => p + c, 0) / arr.length;
const result = average([4, 4, 5, 6, 6]);
console.log(result);
to define the average
function that calls arr.reduce
to return the sum of the entries in arr
.
And we divide the sum by arr.length
array length to get the average.
Then we call average
to return the average of the entries in [4, 4, 5, 6, 6]
.