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.
###
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);
Store the alphabetized index of each element:
$.each(alphabetizedList, function(i)
{
$(this).data("alphaIndex", i);
});
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));
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);
});