mardi 9 juin 2020

using if/else to sort data from an array in order to produce a set of numbers or a string if argument isn't met

I'm a noob, and I'm having a really hard time understanding how to do this with my limited learning so far. The assignment is to sort inputed gpas highest to lowest, to give an average, to pull the highest & lowest, and to separate and output all the gpas above 3.4. I can accomplish this. My problem is that I am trying to have a string outputted stating "no good students this year" if there are NO gpas above 3.4 and I am beating my head against the wall for hours. Can anyone help? Here is the code and my notes:

<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
<div id="output">
  </div>

  <script>
  var gpasOut = [];
  var gpas = [];

  while (gpasOut != "XXX")
  {
     gpasOut = prompt("Enter a GPA or XXX to Stop");

     if (gpasOut != "XXX")
     {
        gpas.push(parseFloat(gpasOut));
     }
  }

// This sets the vars as empty and prompts the user for integers and allows a break with "XXX";
// gpas.push pushes the values from the prompt (gpasOut) into gpas &
// parseFloat turns the strings into floating decimals;

  length = gpas.length;

// This gets the number of integers entered at prompt.

  function totalArray(total, num)
  {
     return total + num;
  }

  var total = gpas.reduce(totalArray);

  // This gets the sum of all numbers in array. Not sure I understand this code, but I was able to make it work.
  // I think it brings the numbers from the right (num) into the number on the left (total), thus "reducing" it.
  //
  // I'm sure there is a better way.

  var average = total / length;
// This gives the average GPA

  var sorted = gpas.sort(function (a, b)
  {
     return b - a
  });

  // This sorts the GPAs highest to lowest. Not sure I understand how it works.
  var badGpas = "<p>There were no good students this year. Try again next year!</p>";
  let goodGpas = [];
  for (let i = 0; i < gpas.length; i++)
  {
     if (gpas[i] >= 3.4)
     {
        goodGpas.push(gpas[i]);
      }

  else {
  badGpas
  }
}

// Here I want to print the string in BadGpas if there were NO gpas above 3.4!


  document.getElementById('output').innerHTML =
    "<h2>GPAs</h2><h3>Sorted Highest to Lowest: </h3>" + sorted.join("<br>")
      +"<h3>Class Average GPA is</h3>" + average + "<br>"
        + "<h3>The Highest is:</h3>" + gpas[0]
          + "<h3>The Lowest is:</h3>" + gpas[gpas.length-1]
            + "<h3>Outstanding GPAs (above 3.4)</h3>" + goodGpas.join("<br>")+badGpas;

  </script>

  </body>
</html>

Aucun commentaire:

Enregistrer un commentaire