Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

169
Visualizações
Sorting and unsorting function

I made script for sorting (A to Z)

My question is what I need to add to this to have unsort function, I mean set to default (how it was before you sort them).

Code:

function sortList() {
  document.getElementById('sortedtxt').innerHTML = 'Sorted A-Z';
  document.getElementById('sortedtitle').innerHTML = 'BFMAS - Sorted A-Z';
  var list, i, switching, b, shouldSwitch;
  list = document.getElementById("sortingUL");
  switching = true;
  while (switching) {
    switching = false;
    b = list.getElementsByTagName("LI");
    for (i = 0; i < (b.length - 1); i++) {
      shouldSwitch = false;
      if (b[i].innerHTML.toLowerCase() > b[i + 1].innerHTML.toLowerCase()) {
        shouldSwitch = true;
        break;
      }
    }
    if (shouldSwitch) {
      b[i].parentNode.insertBefore(b[i + 1], b[i]);
      switching = true;
    }
  }
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Please use this code JS & HTML

  let globalList, temp = [], sorted = true;

  document.getElementById("sort").addEventListener('click', sortList);
  document.getElementById("unsorted").addEventListener('click', UnsortedList);

  function UnsortedList() {
    let currentList = document.getElementById("countries");
    currentList.innerHTML = '';
    temp.forEach(function (item) {
      let li = document.createElement('li');
      currentList.appendChild(li);
      li.innerHTML += item;
    });
    sorted = true;
  }

  function getTempArray(pList) {
    globalList = pList.getElementsByTagName("li");
    temp = [];
    for (let j = 0; j < globalList.length; j++) {
      temp.push(globalList[j].innerText);
    }
  }

  function sortList() {
    let list, i, switching, b, shouldSwitch;
    list = document.getElementById("countries");

    if (sorted === true) {
      getTempArray(list);
      sorted = false;
    }

    switching = true;

    while (switching) {
      switching = false;
      b = list.getElementsByTagName("li");
      for (i = 0; i < (b.length - 1); i++) {
        shouldSwitch = false;
        if (b[i].innerHTML.toLowerCase() > b[i + 1].innerHTML.toLowerCase()) {
          shouldSwitch = true;
          break;
        }
      }
      if (shouldSwitch) {
        b[i].parentNode.insertBefore(b[i + 1], b[i]);
        switching = true;
      }
    }
  }
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>Pues </title>
</head>
<body>
<p>Click the button to sort the list alphabetically 🙂</p>
<button id="sort"><b>Sort</b></button>
<button id="unsorted"><i>Unsorted</i></button>

<ul id="countries">
    <li>Peru</li>
    <li>Argentina</li>
    <li>Brazil</li>
    <li>Colombia</li>
    <li>Paraguay</li>
    <li>Bolivia</li>
</ul>

</body>
</html>

about 4 years ago · Juan Pablo Isaza Relatório

0

First, it seems kind crazy that you are sorting DOM elements in situ (in place), rather than having a separate list data structure (e.g. an array) and treating the DOM as a view... i.e. rendering the list data into the DOM as needed (i.e. after it updates or after you sort it).

Recommendation:

  1. Move the sortedtxt data into an array.
  2. Keep a copy of the array for the original sort order.
  3. create and call a function that renders the array elements into the DOM, e.g. into the appropriate <ul>, <ol> or <table>.
  4. On a user action that changes the sort order or restores the original, apply that to the array and then call the above function again.

Benefits:

  1. Better webpage performance.
  2. Cleaner, simpler that separates data from presentation code.
  3. You can implement fancier sort features such as Sort array of objects by string property value much easier.
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda