Problem with reduce to calculate arithmetic mean of array

Asked

Viewed 266 times

0

Doubt with the method reduce. I cannot perform the arithmetic average calculation, the result even worked once (4,375), however, the code only adds up after a first execution. I’ve checked the documentation, but I still can’t fix it.

var valores = [1.5, 2, 4, 10];

var media = valores.reduce(function (total, item, indice, array) {  
  total = total + item;
    if(indice == array.lenght - 1) {
      return total / array.lenght;
    }
    
    return total;
});

console.log(media);

The code above returns 17.5, whereas it should be 4.375.

2 answers

6

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

  • 1

    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!!!!!

0


Looking at your code, length is spelled wrong (lenght). Fixing this the code starts working:

var valores = [1.5, 2, 4, 10];

var media = valores.reduce(function (total, item, indice, array) {
  total = total + item;

  if(indice == array.length - 1) {
      return total / array.length;
  }
    
  return total;
});

console.log(media);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.