Sorting a list alphabetically with a modulus

后端 未结 4 1945
春和景丽
春和景丽 2021-02-08 20:07

I don\'t have any trouble grabbing a list of elements and sorting them alphabetically, but I\'m having difficulty understanding how to do it with a modulus.

###

4条回答
  •  情歌与酒
    2021-02-08 20:50

    1. Alphabetize your list. This is already done, in your case, but if not:

      function alphabetizeElements(a, b)
      {
          var aText = $(a).text();
          var bText = $(b).text();
          return aText > bText ? 1 : aText < bText ? -1 : 0;
      }
      var alphabetizedList = $("#myList li").sort(alphabetizeElements);
      
    2. Store the alphabetized index of each element:

      $.each(alphabetizedList, function(i)
      {
          $(this).data("alphaIndex", i);
      });
      
    3. Sort the alphabetized list by modulus first, then index:

      function listColumnSortFn(columns)
      {
          return function(a, b)
          {
              var aIndex = $(a).data("alphaIndex");
              var bIndex = $(b).data("alphaIndex");
              return ((aIndex % columns) - (bIndex % columns)) || (aIndex - bIndex);
          }
      }
      var columnSortedList = alphabetizedList.sort(listColumnSortFn(4));
      
    4. Replace the list elements with your sorted elements:

      $("#myList li").remove();
      $("#myList").append(columnSortedList);
      

    Here is the whole thing, all together:

    function sortList(columns)
    {
        var alphabetizedList = $("#myList li").sort(alphabetizeElements);
        $.each(alphabetizedList, function(i)
        {
            $(this).data("alphaIndex", i);
        });
        var columnSortedList = alphabetizedList.sort(listColumnSortFn(columns));
        $("#myList li").remove();
        $("#myList").append(columnSortedList);
    }
    function alphabetizeElements(a, b)
    {
        var aText = $(a).text();
        var bText = $(b).text();
        return aText > bText ? 1 : aText < bText ? -1 : 0;
    }
    function listColumnSortFn(columns)
    {
        return function(a, b)
        {
            var aIndex = $(a).data("alphaIndex");
            var bIndex = $(b).data("alphaIndex");
            return ((aIndex % columns) - (bIndex % columns)) || (aIndex - bIndex);
        }
    }
    $(function()
    {
        sortList(4);
    });
    

提交回复
热议问题