Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

244
Visualizações
Finding the average of an array using JS

I've been looking and haven't found a simple question and answer on stack overflow looking into finding the average of an array.

This is the array that I have

const grades = [80, 77, 88, 95, 68];

I first thought that the answer to this problem would be something like this:

let avg = (grades / grades.length) * grades.length
console.log(avg)

However, this gave me an output of NaN.

So then I tried this:

for (let grade of grades)
    avg = (grade / grades.length) * grades.length
console.log(avg)

This gave me an output of 68. (I'm not sure why).

So with this I have two questions. 1. Why was my output 68? and 2. Could somebody help me out with actually finding the average of an array?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

With ES6 you can turn Andy's solution into as a one-liner:

const average = (array) => array.reduce((a, b) => a + b) / array.length;
console.log(average([1,2,3,4,5]));

over 4 years ago · Santiago Trujillo Relatório

0

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.length;

The reason you got 68 as your result is because in your loop, you keep overwriting your average, so the final value will be the result of your last calculation. And your division and multiplication by grades.length cancel each other out.

over 4 years ago · Santiago Trujillo Relatório

0

For the second part of your question you can use reduce to good effect here:

const grades = [80, 77, 88, 95, 68];

function getAvg(grades) {
  const total = grades.reduce((acc, c) => acc + c, 0);
  return total / grades.length;
}

const average = getAvg(grades);
console.log(average);

The other answers have given good insight into why you got 68, so I won't repeat it here.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda