9
votes

Trier une liste alphabétique avec un module

Je n'ai pas de difficulté à saisir une liste d'éléments et à les trier alphabétiquement, mais j'ai du mal à comprendre comment le faire avec un module.

### Strong> P>

Voici le code de travail "My Way", cependant, j'aime la réévaluation de la réponse fournie ci-dessous plus, alors avez accepté cette réponse. P>

<ul>
    <li><a href="~">Boots</a></li>
    <li><a href="~">Helmet Accessories</a></li>
    <li><a href="~">Pants</a></li>
    <li><a href="~">Riding Suits</a></li>
    <li><a href="~">Eyewear</a></li>
    <li><a href="~">Helmets</a></li>
    <li><a href="~">Protection</a></li>
    <li><a href="~">Riding Underwear</a></li>
    <li><a href="~">Gloves</a></li>
    <li><a href="~">Jackets</a></li>
    <li><a href="~">Rainwear</a></li>
    <li><a href="~">Socks</a></li>
    <li><a href="~">Heated Gear</a></li>
    <li><a href="~">Mechanic's Wear</a></li>
    <li><a href="~">Random Apparel</a></li>
    <li><a href="~">Vests</a></li>
</ul>


4 commentaires

Pourriez-vous poster le code que vous avez déjà?


Et, en supposant que vous développiez cela à partir d'un backend, pourquoi ne faites-vous pas cela sous le serveur?


Il y a en fait une solution CSS à cela, avec nombre de colonnes


Une solution de backend serait idéale, mais pas possible dans cette circonstance. Ce que j'ai jusqu'à présent, explose et ne serait pas un endroit idéal pour commencer.


4 Réponses :


0
votes
var columnify = function (a,n) { 
    var result = []; 
    for (var i = 0, lastIndex = a.length - 1; i < lastIndex; i++) 
       result.push(a[i * n % (lastIndex)]); 
    result[lastIndex] = a[lastIndex];
    return result; 
}

var products = ["Boots",
"Eyewear",
"Gloves",
"Heated Gear",
"Helmet Accessories",
"Helmets",
"Jackets",
"Mechanic's Wear",
"Pants",
"Protection",
"Rainwear",
"Random Apparel",
"Riding Suits",
"Riding Underwear",
"Socks",
"Vests",]

columnify(products, 4)
["Boots", "Helmet Accessories", "Pants", "Riding Suits", "Eyewear", "Helmets", "Protection", "Riding Underwear", "Gloves", "Jackets", "Rainwear", "Socks", "Heated Gear", "Mechanic's Wear", "Random Apparel", "Vests"]
Apply that function to the already sorted list, and then it will return a list of strings in the order (almost) that you want. Then add the list that was returned in order to the unordered list in the DOM.Also, I haven't tested it with anything besides that list. So I'd do that if I were you. From what I see, it only works if the length of the list is a multiple of n. Not that great of a solution but it's late for me and I can't be bothered to come up with anything better.EDIT: fixed the issue with the last element

2 commentaires

La théorie est assez sain mais la mise en œuvre n'est pas correcte. Passant dans un tableau de 17 éléments avec n = 4 rendements 0 4 8 12 quatre fois avec une dernière 16 de la cinquième rangée.


@EMTUCIDIFOR: Oui. Comme je l'ai dit, cela ne fonctionne pas quand n% longueur! = 0.



0
votes

Voir si cela fonctionnera: http://jsfiddle.net/6xm9m/2

var newList = new Array();
var listItem = $('#list > li');
var mod = 4;
var colCount = Math.ceil(listItem.length / mod);

listItem.each(function(index) {
    var newIndex = ((index % colCount) * mod) + Math.floor(index / colCount);
    // $(this).text(newIndex);

    newList[newIndex] = this;
});

$('#list').empty();

for(var i = 0; i < newList.length; i++){
    $('#list').append(newList[i]);
}


0 commentaires

0
votes

Vous allez. Le code est étonnamment simple une fois que vous avez compris. Je me rends compte que vous utilisez jQuery mais je ne suis pas assez familier avec elle pour utiliser ses caractéristiques. C'est assez simple que cela ne soit peut-être pas nécessaire.

<html>
<head>
<style type="text/css">
a.panelnum {
   display:block;
   float:left;
   width:40px;
   height:40px;
   border:1px solid black;
   text-align:center;
   vertical-align:middle;
   text-decoration:none;
   font-size:2em;
}
</style>
</head>
<body onload="doit(17, 4);">
<div id="output" style="border:1px solid blue;">
</div>
<script type="text/javascript">

function pivotArray(arr, columns) {
   var l = arr.length, out = [], ind = 0, i = 0;
   for (; i < l; i += 1) {
      out[ind] = arr[i];
      ind += columns;
      if (ind >= l) {
         ind = ind % columns + 1;
      }
   }
   return out;
}

function doit(size, columns) {
   document.getElementById('output').innerHTML = 'starting';
   var l = size;
   var inp = [];
   for (var i = 0; i < l; i += 1) {
      inp[i] = i;   
   }
   var result = pivotArray(inp, columns);
   var str = '';
   for (i = 0; i < l; i += 1) {
      str += '<a class="panelnum">' + result[i] + '</a>';
   }
   var d = document.getElementById('output')
   d.innerHTML = '<p>Some pre text</p>' + str + '<p style="clear:both;">and some post text</p>';
   d.style.width = (columns * d.childNodes[1].offsetWidth + 2) + 'px';
}
</script>
</body>
</html>


0 commentaires

2
votes
  1. alphabétisez votre liste. Ceci est déjà fait, dans votre cas, mais sinon: p>

    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);
    });
    
  2. stocker l'index alphabétisé de chaque élément: p>

    $("#myList li").remove();
    $("#myList").append(columnSortedList);
    
  3. Trier la liste alphabétisée par MODULUS, puis Index: P>

    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. Remplacez les éléments de la liste avec vos éléments triés: P>

    $.each(alphabetizedList, function(i)
    {
        $(this).data("alphaIndex", i);
    });
    

0 commentaires