It is even possible to do all this using the reduce
, but it is not ideal, since there is a need to create a code more complicated than necessary.
To another answer explains why the original code didn’t work, but the reduce
should not be used for everything (as many people think). Note that it is much more "trivial" to simply use the reduce
to sum the elements of which, in addition to adding, check if it is the last element to finally perform the division.
In short, you don’t need to use the reduce
to calculate the average. If you are going to use it, it should only be to reduce all the numbers in the list into one (adding them together).
Once this reduction has been made, you can calculate the mean (by dividing the sum result by the length of the original array, that is, the number of elements).
Thus:
function media(numeros) {
const total = numeros.reduce((total, atual) => {
return total + atual;
});
return total / numeros.length;
}
console.log(media([10, 20, 30, 40])); // 25
Note that it is not even necessary to use reduce
. Some people may find the following simpler:
function media(numeros) {
let total = 0;
for (const numero of numeros) {
total += numero;
}
return total / numeros.length;
}
console.log(media([10, 20, 30, 40])); // 25
It is not really ideal, but I am only studying to solve doubts, and with ctz I will follow the tips left, I appreciate the patience and understanding to explain, show!!!!!
– Yvan Rondon