Ir ao conteúdo
  • Cadastre-se

Javascript calcular média com reduce


Posts recomendados

Eu tenho uma dúvida de como fazer a média. Supomos que tenho esse exercício:

 

<p>1) Click to sort the numbers you tipped</p>
<button onclick="myFunction()">Sort</button>
<p>2) Click to sort the numbers from largest to smallest</p>
<button onclick="myFunction2()">Sort</button>
<p>3) Click to see the Average</p>
<button onclick="myFunction3()">Sort</button>
<p>4) Click to see the Highest</p>
<button onclick="myFunction4()">Sort</button>
<p>5) Click to see the Lowest</p>
<button onclick="myFunction5()">Sort</button>
<div id="output"></div>
<script>
var gpas = [];
var theGPA = "";
//
while (theGPA != "exit")
{
theGPA = prompt("Enter a GPA or exit to Stop");
if(theGPA != "exit"){
gpas.push(theGPA);
}
}
//
var out = "";
for(var x = 0; x < gpas.length; x++)
{
out += gpas[x];
out += " ";
}
document.getElementById('output').innerHTML = "Tipped numbers: <br>" + out;
//function sort
function myFunction(){
  gpas.sort();
  document.getElementById('output').innerHTML = "Sorted numbers: <br>" + gpas;
}
//function sort largest to smallest
function myFunction2(){
  gpas.sort(function(a,b){
    return b - a;
  });
document.getElementById('output').innerHTML = "From the largest to smallest: <br>" + gpas;
}
/*
var total = 0;
for(var x = 0; x < gpas.length; x++){
  total += gpas[x];
var avg = total/gpas.length;
}*/
function myFunction3(){
let total = gpas.reduce((a, b) => a + b);
let avg = total/gpas.length;
document.getElementById('output').innerHTML = "The Average is: <br>" + avg;
}
function myFunction4(){
  gpas.sort(function(a,b){
    return b - a;
  });
  document.getElementById('output').innerHTML = "Highest: <br>" + gpas[0];
}
function myFunction5(){
  gpas.sort(function(a,b){
    return a - b;
  });
  document.getElementById('output').innerHTML = "Lowest: <br>" + gpas[0];
}
</script>

Como eu faço para realizar o cálculo da média. Com o reduce não tô conseguindo ou estou implementando de maneira incorreta.

Link para o comentário
Compartilhar em outros sites

Crie uma conta ou entre para comentar

Você precisa ser um usuário para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar agora

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...

 

GRÁTIS: ebook Redes Wi-Fi – 2ª Edição

EBOOK GRÁTIS!

CLIQUE AQUI E BAIXE AGORA MESMO!