RinoDrummer

Sorting a list using JS

Jan 18th, 2021
562
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const list = document.getElementById('list');
  2.  
  3. const sortByAlpha = () => {
  4.  
  5.     return Array.from(list.children)
  6.     .sort(function(a, b) {
  7.         var nameA = a.textContent.toUpperCase();
  8.         var nameB = b.textContent.toUpperCase();
  9.         if (nameA < nameB) {
  10.           return -1;
  11.         }
  12.         if (nameA > nameB) {
  13.           return 1;
  14.         }
  15.  
  16.         return 0;
  17.       });
  18. };
  19.  
  20. // When updating...
  21.  
  22. let sortedElems = sortByAlpha();
  23.  
  24. list.innerHTML = '';
  25.  
  26. for (let i = 0; i < sortedElems.length; i++) {
  27.     list.appendChild(sortedElems[i]);
  28. }
RAW Paste Data