Как отсортировать список из пользовательского ввода с наименьшего значения на наибольшее значение в HTML - PullRequest
0 голосов
/ 22 марта 2019

Я пытаюсь создать код, который будет давать сумму, среднее, минимальное, максимальное и частоту чисел в списке, а также сортирует список от минимального значения к наибольшему значению. С помощью других я смог получить сумму, среднее, максимальное, минимальное и частоту, но не смог понять, как отсортировать список от наивысшего значения к наименьшему. То, что я хочу от кода, это иметь кнопку в конце кода

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

, который пользователь может нажать, чтобы отсортировать список от минимального значения к наибольшему значению.

Ответы [ 3 ]

1 голос
/ 22 марта 2019

, поскольку вы используете числа в качестве значений элементов списка, мы можем отсортировать их по числовому массиву, как это.

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>
1 голос
/ 22 марта 2019

Простой пример, который работает в вашем случае, https://www.w3schools.com/howto/howto_js_sort_list.asp

Вы просто должны изменить его с алфавитного на числовой. Здесь вы можете отсортировать список от низшего к высшему & от наивысшего к низшему , а затем переупорядочить элементы в DOM.

низкий-высокий

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

Высокий-низкий

// 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>
0 голосов
/ 22 марта 2019

Я предоставил 2 решения; обновленная версия, которая не хранит и не вычисляет значения при каждом обновлении (версия 1), и другая версия, которая является вашим собственным расширением (версия 2):

Версия 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>

Версия 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>

Надеюсь, это поможет,

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...