1

I'm trying to make a code that will evaluate numbers in a list from user input and will calculate the sum, average, minimum, and maximum of that list. I have already gotten the sum part from help from others. I can't seem to find how to get the maximum and minimum numbers from the list. Im trying to have all of the functions (sum, average, max, and min) as buttons just like the sum button that is already in the code and when clicked on it will alert the user of that specific function.

.title { font-weight:bold; margin-top:1em; }
<!DOCTYPE html>

<html>
<head>
  
  <link rel="stylesheet" type="text/css" href="style.css">
  
  </head>
  
  
<body>

  <!--- This only allows the user to input numbers --->
  
  <input type='number' id='input'>
  
  <!--- This is the button that adds the number to the list --->
  
  <input type='button' value='add to list' id='add' disabled="disabled">

  
  <!--- This will list all of the numbers in the list --->
  
  <div class="title">Topics</div>
  <ul id='list'></ul> 
  
   <!--- When clicked, this will alert the user with the sum of their numbers --->
  
  <button id="something">Click Here To See The Sum</button>

  <script>
    
    let list = document.getElementById("list");;
    let btn = document.getElementById("something");
    let input = document.getElementById("input");
    let add = document.getElementById("add");
    
    var sum = 0;
    
    input.addEventListener("input", enableDisable);
    btn.addEventListener("click", sumvar);

    add.addEventListener("click", function() {
      var li = document.createElement("li");
      li.textContent = input.value;
      sum += +input.value; 
      list.appendChild(li);
      input.value = "";  
      add.disabled = "disabled";
    });
   
    // This allows the "add to list" button to be turned on/off depending if the user has typed in a number
      
    function enableDisable(){
     
      if(this.value === ""){
        add.disabled = "disabled";
      } else {
        add.removeAttribute("disabled");
      }
    }
    
    // This function will alert the user of the sum of their numbers
      
    function sumvar() {
      alert("The sum of your numbers is: " + sum);
    }
    
    
  </script>   


</body>
  

  
  
</html>
Max Muchnick
  • 55
  • 4
  • 9

3 Answers3

2

You could add the following two functions at the top of your script:

    function getNumbersFromList() {
        let numbers = [];
        for (let i = 0; i < list.children.length; i++) {
            numbers.push(parseInt(list.children.item(i).textContent));
        }
        return numbers;
    }

    function getStatsForList() {
        let numbers = getNumbersFromList();
        return {
            sum: numbers.reduce((a, v) => a += v),
            average: numbers.reduce((a, v) => a += v) / numbers.length,
            max: Math.max(...numbers),
            min: Math.min(...numbers)
        }
    }

And then you could use getStatsForList() when you need the updated statistics for your sample.

That function could also easily be modified to add more statistics if needed...

Update

This version only computes the sum once and uses it later to compute the average.

    function getStatsForList() {
        let numbers = getNumbersFromList();
        let sum = numbers.reduce((a, v) => a += v);
        return {
            sum: sum,
            average: sum / numbers.length,
            max: Math.max(...numbers),
            min: Math.min(...numbers)
        }
    }
focorner
  • 1,927
  • 1
  • 20
  • 24
  • 1
    Loved the Math.max/min use with ES6, really readable (needs babel for old browsers). Not sure if those two reduces will have an impact as the list grows. – rafaelcastrocouto Mar 21 '19 at 23:37
  • 1
    @rafaelcastrocouto I agree that computing the sum twice (once for the sum and once for the average) is unnecessary here. It should be done once for the sum and re-used for the average. – focorner Mar 21 '19 at 23:44
1

let list = document.getElementById("list");
let input = document.getElementById("input");
let add = document.getElementById("add");
var avg = 0;
var sum = 0;
var min = Infinity;
var max = -Infinity;

// This will add the input number to the list and clear the input

function addClick () {
  var li = document.createElement("li");
  li.textContent = input.value;
  list.appendChild(li);
  update();
  input.value = "";  
  add.disabled = "disabled";
} 

// This allows the "add to list" button to be turned on/off depending if the user has typed in a number

function enableDisable(){
  if(this.value === ""){
    add.disabled = "disabled";
  } else {
    add.removeAttribute("disabled");
  }
}

// This will calculate and update all variable values

function update() {
  sum = 0;
  min = Infinity;
  max = -Infinity;
  var count = 0;
  for (var i of list.children) {
    let val = +i.textContent;
    sum += val;
    if (val > max) max = val;
    if (val < min) min = val;
    count++;
  }
  avg = sum/count;
} 

// This functions will alert the numbers

function sumClick() {
  alert("The sum of your numbers is: " + sum);
}
function avgClick() {
  alert("The average of your numbers is: " + avg);
}
function minClick() {
  alert("The smaller number is: " + min);
}
function maxClick() {
  alert("The greater number is: " + max);
} 

// Here we add all events

input.addEventListener("input", enableDisable);
add.addEventListener("click", addClick);
document.getElementById("avg").addEventListener("click", avgClick);
document.getElementById("sum").addEventListener("click", sumClick); 
document.getElementById("min").addEventListener("click", minClick); 
document.getElementById("max").addEventListener("click", maxClick);
.title { font-weight:bold; margin-top:1em; }
<!--- This only allows the user to input numbers --->
  
  <input type='number' id='input'>
  
  <!--- This is the button that adds the number to the list --->
  
  <input type='button' value='add to list' id='add' disabled="disabled">

  <!--- Here we have a title for the list --->

  <div class="title">Topics</div>

  <!--- This will list all of the numbers --->

  <ul id='list'></ul> 
  
   <!--- When clicked, this buttons alert the user with the numbers --->
  
  <button id="sum">Sum</button>
  <button id="max">Max</button>
  <button id="min">Min</button>
  <button id="avg">Avg</button>
rafaelcastrocouto
  • 11,781
  • 3
  • 38
  • 63
  • 1
    This works perfectly except for the minimum value. When I enter in the numbers 1,2,3,4,5 and click the "min" button it says that the value is infinity. This only happens when the minimum value is in the first spot of the list. How do I fix this? – Max Muchnick Mar 21 '19 at 23:37
  • It was a typo, I also spotted it and fixed right after posting. – rafaelcastrocouto Mar 21 '19 at 23:38
  • I copied the new snippet and I still don't know how to fix this. The minimum value does work, just not when the minimum value is the first value. If I enter 0,1,2,3 and click "min" I get prompted with Infinity. When I enter in 1,2,3,0 the minimum is 0. – Max Muchnick Mar 21 '19 at 23:45
  • 1
    I actually figured it out. Thanks for the help works perfectly now. – Max Muchnick Mar 21 '19 at 23:51
0

You can keep track of the current min, max and count of items, as new items are added compare mins and maxes and calculate the average.

.title { font-weight:bold; margin-top:1em; }
<!DOCTYPE html>

<html>
<head>
  
  <link rel="stylesheet" type="text/css" href="style.css">
  
  </head>
  
  
<body>

  <!--- This only allows the user to input numbers --->
  
  <input type='number' id='input'>
  
  <!--- This is the button that adds the number to the list --->
  
  <input type='button' value='add to list' id='add' disabled="disabled">

  
  <!--- This will list all of the numbers in the list --->
  
  <div class="title">Topics</div>
  <ul id='list'></ul> 
  
   <!--- When clicked, this will alert the user with the sum of their numbers --->
  
  <button id="something">Click Here To See The Sum</button>

  <script>
    
    
    
    let list = document.getElementById("list");;
    let btn = document.getElementById("something");
    let input = document.getElementById("input");
    let add = document.getElementById("add");
    var firstLoad = 1;
    var sum = 0;
    var avg = 0;
    var min = 0;
    var max = 0;
    var count = 0;
    input.addEventListener("input", enableDisable);
    btn.addEventListener("click", sumvar);

    add.addEventListener("click", function() 
    { 
      var li = document.createElement("li");
      li.textContent = input.value;
      sum += +input.value; 
      count=count+1;
       
      if(firstLoad===1) { 
       min = input.value; //set min and max first time
        max = input.value;
        firstLoad = 0; //clear the firstload marker
      }
      else
      {
      
        if(min > input.value) { //compare input to min
           min = input.value;
        }
        if(max < input.value) { //compare input to max
          max = input.value; //enteredNumber;
        }
      }
      avg = sum/count; //calculate average
      list.appendChild(li);
      input.value = "";  
      add.disabled = "disabled";
    });
    
    function enableDisable() { 
      if(this.value === ""){
        add.disabled = "disabled";
      } else {
        add.removeAttribute("disabled");
      }
    }
    
    // This function will alert the user of the sum of their numbers
      
    function sumvar() {
      alert("sum:" + sum + ",avg:" + avg + ",min:" + min + ",max:" + max);
    }
    
    
  </script>   


</body>
  

  
  
</html>
L0uis
  • 703
  • 5
  • 8