How may I sort a list alphabetically using jQuery?

后端 未结 10 2139
灰色年华
灰色年华 2020-11-21 23:13

I\'m a bit out of my depth here and I\'m hoping this is actually possible.

I\'d like to be able to call a function that would sort all the items in my list alphabeti

相关标签:
10条回答
  • 2020-11-21 23:32

    @SolutionYogi's answer works like a charm, but it seems that using $.each is less straightforward and efficient than directly appending listitems :

    var mylist = $('#list');
    var listitems = mylist.children('li').get();
    
    listitems.sort(function(a, b) {
       return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
    })
    
    mylist.empty().append(listitems);
    

    Fiddle

    0 讨论(0)
  • 2020-11-21 23:33

    If you are using jQuery you can do this:

    $(function() {
    
      var $list = $("#list");
    
      $list.children().detach().sort(function(a, b) {
        return $(a).text().localeCompare($(b).text());
      }).appendTo($list);
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    
    <ul id="list">
      <li>delta</li>
      <li>cat</li>
      <li>alpha</li>
      <li>cat</li>
      <li>beta</li>
      <li>gamma</li>
      <li>gamma</li>
      <li>alpha</li>
      <li>cat</li>
      <li>delta</li>
      <li>bat</li>
      <li>cat</li>
    </ul>

    Note that returning 1 and -1 (or 0 and 1) from the compare function is absolutely wrong.

    0 讨论(0)
  • 2020-11-21 23:36

    You do not need jQuery to do this...

    function sortUnorderedList(ul, sortDescending) {
      if(typeof ul == "string")
        ul = document.getElementById(ul);
    
      // Idiot-proof, remove if you want
      if(!ul) {
        alert("The UL object is null!");
        return;
      }
    
      // Get the list items and setup an array for sorting
      var lis = ul.getElementsByTagName("LI");
      var vals = [];
    
      // Populate the array
      for(var i = 0, l = lis.length; i < l; i++)
        vals.push(lis[i].innerHTML);
    
      // Sort it
      vals.sort();
    
      // Sometimes you gotta DESC
      if(sortDescending)
        vals.reverse();
    
      // Change the list on the page
      for(var i = 0, l = lis.length; i < l; i++)
        lis[i].innerHTML = vals[i];
    }
    

    Easy to use...

    sortUnorderedList("ID_OF_LIST");
    

    Live Demo →

    0 讨论(0)
  • 2020-11-21 23:40

    HTML

    <ul id="list">
        <li>alpha</li>
        <li>gamma</li>
        <li>beta</li>
    </ul>
    

    JavaScript

    function sort(ul) {
        var ul = document.getElementById(ul)
        var liArr = ul.children
        var arr = new Array()
        for (var i = 0; i < liArr.length; i++) {
            arr.push(liArr[i].textContent)
        }
        arr.sort()
        arr.forEach(function(content, index) {
            liArr[index].textContent = content
        })
    }
    
    sort("list")
    

    JSFiddle Demo https://jsfiddle.net/97oo61nw/

    Here we are push all values of li elements inside ul with specific id (which we provided as function argument) to array arr and sort it using sort() method which is sorted alphabetical by default. After array arr is sorted we are loop this array using forEach() method and just replace text content of all li elements with sorted content

    0 讨论(0)
  • 2020-11-21 23:41
    $(".list li").sort(asc_sort).appendTo('.list');
    //$("#debug").text("Output:");
    // accending sort
    function asc_sort(a, b){
        return ($(b).text()) < ($(a).text()) ? 1 : -1;    
    }
    
    // decending sort
    function dec_sort(a, b){
        return ($(b).text()) > ($(a).text()) ? 1 : -1;    
    }
    

    live demo : http://jsbin.com/eculis/876/edit

    0 讨论(0)
  • 2020-11-21 23:43

    I was looking to do this myself, and I wasnt satisfied with any of the answers provided simply because, I believe, they are quadratic time, and I need to do this on lists hundreds of items long.

    I ended up extending jquery, and my solution uses jquery, but could easily be modified to use straight javascript.

    I only access each item twice, and perform one linearithmic sort, so this should, I think, work out to be a lot faster on large datasets, though I freely confess I could be mistaken there:

    sortList: function() {
       if (!this.is("ul") || !this.length)
          return
       else {
          var getData = function(ul) {
             var lis     = ul.find('li'),
                 liData  = {
                   liTexts : []
                }; 
    
             for(var i = 0; i<lis.length; i++){
                 var key              = $(lis[i]).text().trim().toLowerCase().replace(/\s/g, ""),
                 attrs                = lis[i].attributes;
                 liData[key]          = {},
                 liData[key]['attrs'] = {},
                 liData[key]['html']  = $(lis[i]).html();
    
                 liData.liTexts.push(key);
    
                 for (var j = 0; j < attrs.length; j++) {
                    liData[key]['attrs'][attrs[j].nodeName] = attrs[j].nodeValue;
                 }
              }
    
              return liData;
           },
    
           processData = function (obj){
              var sortedTexts = obj.liTexts.sort(),
                  htmlStr     = '';
    
              for(var i = 0; i < sortedTexts.length; i++){
                 var attrsStr   = '',
                     attributes = obj[sortedTexts[i]].attrs;
    
                 for(attr in attributes){
                    var str = attr + "=\'" + attributes[attr] + "\' ";
                    attrsStr += str;
                 }
    
                 htmlStr += "<li "+ attrsStr + ">" + obj[sortedTexts[i]].html+"</li>";
              }
    
              return htmlStr;
    
           };
    
           this.html(processData(getData(this)));
        }
    }
    
    0 讨论(0)
提交回复
热议问题