recently I tried to calculate Average with the Reduce Method In JavaScript here is may code
var arr = [129, 139, 155, 176];
var result = arr.reduce(function (start, end, index, array){
var total =start + end;
var array_length = array.length;
return total/array_length;
});
console.log(result);
my result is 57.875 but it's wrong, where is my problem and how to resolve it?
Average or Arithmetic mean of an array using JavascriptIts value can be obtained by calculating the sum of all the values in a set and dividing the sum by the number of values.
The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.
You calculate an average by adding all the elements and then dividing by the number of elements. var total = 0; for(var i = 0; i < grades. length; i++) { total += grades[i]; } var avg = total / grades.
reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left-to-right) and the return value of the function is stored in an accumulator.
You could add all values, who are divided by the length to get the average.
var array = [129, 139, 155, 176],
average = array.reduce(function (avg, value, _, { length }) {
return avg + value / length;
}, 0);
console.log(average);
Or take the sum of all values and divide by the length of the array. The result is the same.
var array = [129, 139, 155, 176],
average = array.reduce(function (sum, value) {
return sum + value;
}, 0) / array.length;
console.log(average);
You have repeated reduce on each item of the array. What the other answers are doing they havent reduced the array into the average result, instead they did sum and then reduced and you needed 2 steps to do that.
The good functional programmers, we wanna think as one "pure, one shot" way to transform our input data into the thing we really want. This should leave almost a little bit of code smell.
The better way to do that is you can use couple of supported arguments of the reduce function.
See the code and hope that helps with your answer. Happy coding :)
var arr = [129, 139, 155, 176];
function reducer(acc, value, index, array) {
var calculatedValue = acc + value;
if (index === array.length - 1) {
return calculatedValue / array.length;
}
return calculatedValue;
}
var result = arr.reduce(reducer, 0);
console.log(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With