0

I'm trying to make a code that will give the sum, average, min, max, and frequency of numbers in a list and also sorts the list from lowest value to highest value. With the help of others, I was able to get the sum, average, max, min, and frequency, but could not figure out how to sort the list from highest value to lowest value. What I want from the code is to have a button at the end of the code

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

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

    <link rel="stylesheet" type="text/css" href="style.css">
<!--- 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>
<button id="frequency"> Frequency </button>


<div>

  <button value="Refresh Page" onclick="window.location.reload()"> Reset! </button>

</div>
  
  <script>
    
    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;
let frequency = Object.create(null);

// 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);
  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(enteredValue) {
  frequency[enteredValue] = (frequency[enteredValue] || 0) + 1;
  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;
}

function frequencyClick() {
  let text = Object.entries(frequency).reduce((a, [number, fqy]) => {
    return a.concat(`The number ${number} appeared ${fqy} time(s) in the list`)
  }, []).join('\n');
  
  alert(text);
}

// 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);
document.getElementById("frequency").addEventListener("click", frequencyClick);
    
    
  </script>   


</body>
  

  
  
</html>

that the user can press to sort the list from lowest value to highest value.

1
  • 1
    You could have an array to store all the numbers. And use array.sort() to have it well-sorted then re-render it to the html dom. Commented Mar 22, 2019 at 1:56

3 Answers 3

1

Simple example that works in your case, https://www.w3schools.com/howto/howto_js_sort_list.asp

You just have to simply change it from organizing alphabetically to numerically. Here you go, sort a list lowest to highest & highest to lowest, then re-arrange the elements on the DOM.

Low-high

function lowHigh() {
    var list, i, switching, b, shouldSwitch;
    list = document.getElementById("list");
    switching = true;
    /* Make a loop that will continue until
    no switching has been done: */
    while (switching) {
        // Start by saying: no switching is done:
        switching = false;
        b = list.getElementsByTagName("li");
        // Loop through all list items:
        for (i = 0; i < (b.length - 1); i++) {
            // Start by saying there should be no switching:
            shouldSwitch = false;
            /* Check if the next item should
            switch place with the current item: */
            if (b[i].innerText > b[i + 1].innerText) {
                shouldSwitch = true;
                break;
            }
        }
        if (shouldSwitch) {
            /* If a switch has been marked, make the switch
            and mark the switch as done: */
            b[i].parentNode.insertBefore(b[i + 1], b[i]);
            switching = true;
        }
    }

High-low

// Change to
if (b[i].innerText < b[i + 1].innerText) 

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;
let frequency = Object.create(null);

// 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);
  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(enteredValue) {
  frequency[enteredValue] = (frequency[enteredValue] || 0) + 1;
  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;
}

function frequencyClick() {
  let text = Object.entries(frequency).reduce((a, [number, fqy]) => {
    return a.concat(`The number ${number} appeared ${fqy} time(s) in the list`)
  }, []).join('\n');

  alert(text);
}

// 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);
}

function lowHigh() {
  var list, i, switching, b, shouldSwitch;
  list = document.getElementById("list");
  switching = true;
  /* Make a loop that will continue until
  no switching has been done: */
  while (switching) {
    // Start by saying: no switching is done:
    switching = false;
    b = list.getElementsByTagName("li");
 
    // Loop through all list items:
    for (i = 0; i < (b.length - 1); i++) {
      // Start by saying there should be no switching:
      shouldSwitch = false;
      /* Check if the next item should
      switch place with the current item: */
      if (b[i].innerText > b[i + 1].innerText) {
        shouldSwitch = true;
        break;
      }
    }
    if (shouldSwitch) {
      /* If a switch has been marked, make the switch
      and mark the switch as done: */
      b[i].parentNode.insertBefore(b[i + 1], b[i]);
      switching = true;
    }
  }


}

// 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);
document.getElementById("frequency").addEventListener("click", frequencyClick);
<!DOCTYPE html>

<html>

<head>

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

</head>


<body>

  <link rel="stylesheet" type="text/css" href="style.css">
  <!--- 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>
  <button id="frequency"> Frequency </button>

  <p><button onclick="lowHigh()">Sort</button></p>


  <div>

    <button value="Refresh Page" onclick="window.location.reload()"> Reset! </button>

  </div>



</body>



</html>

Sign up to request clarification or add additional context in comments.

Comments

1

because you are using numbers as list item values, we can sort it with number array like this.

var list = document.getElementById('list');
function sort(dir){
	var li = list.getElementsByTagName("li");
	// populate data into array
	var data=[];
	for(var a in li) {
		if (typeof li[a].innerText !='undefined') data.push(parseInt(li[a].innerText,10));
	}
	// create sort number function as sort parameter, we need this because default sort function will sort it alphabetically
	var sortNum = function (a,b) {
        return a - b;
    }
	// start sorting
	if (dir == 'asc') data.sort(sortNum);
	else data.sort(sortNum).reverse();
	// clear list
	while (list.lastChild) {
		list.removeChild(list.lastChild);
	}
	// generate new list items
	for (var x=0; x<data.length; x++) {
		var new_li = document.createElement("li");
		new_li.textContent = data[x];
		list.appendChild(new_li);
	}
}
<input type="button" value="asc" onclick="sort('asc')"><input type="button" value="desc" onclick="sort('desc')"> 
<ul id="list">
  <li>2</li>
  <li>3</li>
  <li>16</li>
  <li>21</li>
  <li>15</li>
</ul>

Comments

0

I have provided 2 solutions; an updated version that doesn't store and compute values on every update (version 1) and another version which is an extension of your own (version 2):

Version 1:

let list = document.getElementById("list");
let input = document.getElementById("input");
let add = document.getElementById("add");

let items = [];
addItem = () => {
  var li = document.createElement("li");
  li.textContent = input.value;
  list.appendChild(li);
  items.push(+input.value);
  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 functions will alert the numbers
// You can pull these out into functions if you would like. 
getSum = () => alert(`The sum of your numbers is: ${items.reduce((acc, v)=>acc+=v,0)}`);
getAvg = () => alert(`The average of your numbers is: ${items.reduce((acc, v)=>acc+=v,0)/items.length}`);
getMin = () => alert(`The smaller number is: ${Math.min(...items)}`);
getMax = () => alert(`The greater number is: ${Math.max(...items)}`);
getAscending = () => alert(JSON.stringify(items.sort(), null, 4));
getDescending = () => alert(JSON.stringify(items.sort((a, b) => b - a), null, 4));
getFrequency = () => alert(
  Object.entries(items.reduce((acc, v) => {
    if (acc[v]) {
      acc[v]++;
    } else {
      acc[v] = 1;
    }
    return acc;
  }, {})).map(([number, fqy]) =>
    `The number ${number} appeared ${fqy} time(s) in the list`
  ).join("\n"));
.title {
  font-weight: bold;
  margin-top: 1em;
}
<!DOCTYPE html>

<html>

<head>

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

</head>


<body>

  <link rel="stylesheet" type="text/css" href="style.css">
  <!--- This only allows the user to input numbers --->

  <input type='number' id='input' oninput="enableDisable()">

  <!--- This is the button that adds the number to the list --->

  <input type='button' value='add to list' id='add' onClick="addItem()" 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 onClick="getSum()"> Sum </button>
  <button onClick="getMax()"> Max </button>
  <button onClick="getMin()"> Min </button>
  <button onClick="getAvg()"> Avg </button>
  <button onClick="getFrequency()"> Frequency </button>
  <button onClick="getAscending()"> Sort Ascending </button>
  <button onClick="getDescending()"> Sort Descending </button>

  <div>
    <button value="Refresh Page" onclick="window.location.reload()"> Reset! </button>
  </div>
</body>

</html>

Version 2:

var list = document.getElementById("list");
var input = document.getElementById("input");
var add = document.getElementById("add");
var avg = 0;
var sum = 0;
var min = -Infinity;
var max = Infinity;
var frequency = Object.create(null);
var ascending = [];
var descending = [];

// 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);
  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(enteredValue) {
  frequency[enteredValue] = (frequency[enteredValue] || 0) + 1;
  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;
  ascending = Object.keys(frequency).sort();
  descending = Object.keys(frequency).sort((a, b) => b - a);
}

function frequencyClick() {
  let text = Object.entries(frequency).reduce((a, [number, fqy]) => {
    return a.concat(`The number ${number} appeared ${fqy} time(s) in the list`)
  }, []).join('\n');

  alert(text);
}

// 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);
}

function ascending() {}

function descending() {}

// 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);
document.getElementById("frequency").addEventListener("click", frequencyClick);
document.getElementById("ascending").addEventListener("click", () => alert(JSON.stringify(ascending, null, 4)));
document.getElementById("descending").addEventListener("click", () => alert(JSON.stringify(descending, null, 4)));
.title {
  font-weight: bold;
  margin-top: 1em;
}
<!DOCTYPE html>

<html>

<head>

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

</head>


<body>

  <link rel="stylesheet" type="text/css" href="style.css">
  <!--- 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>
  <button id="frequency"> Frequency </button>
  <button id="ascending"> Sort Ascending </button>
  <button id="descending"> Sort Descending </button>

  <div>
    <button value="Refresh Page" onclick="window.location.reload()"> Reset! </button>
  </div>
</body>

</html>

Hope this helps,

1 Comment

Err. Dang, I had made it actually re-arrange the elements, that's what I thought he wanted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.