How May I Sort a List Alphabetically Using Jquery

How may I sort a list alphabetically using jQuery?

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 →

Alphabetize a list using JS or jQuery

There is no need for jQuery, you can use Vanilla JavaScript. ;)

  1. Take the parent element (recommend id as identifier)
  2. Convert node list to array, because sorting will then be easy
  3. Sort array by custom criteria "element.innerText" is the visible part
  4. Move item by item to the end in correct order

    // selector to parent element (best approach by id)
    var parent = document.querySelector("ul"),
    // take items (parent.children) into array
    itemsArray = Array.prototype.slice.call(parent.children);

    // sort items in array by custom criteria
    itemsArray.sort(function (a, b) {
    // inner text suits best (even when formated somehow)
    if (a.innerText < b.innerText) return -1;
    if (a.innerText > b.innerText) return 1;
    return 0;
    });

    // reorder items in the DOM
    itemsArray.forEach(function (item) {
    // one by one move to the end in correct order
    parent.appendChild(item);
    });

It is hundred times faster than jQuery, check the performance comparison charts http://clubmate.fi/append-and-prepend-elements-with-pure-javascript/

Sorting options elements alphabetically using jQuery

What I'd do is:

  1. Extract the text and value of each <option> into an array of objects;
  2. Sort the array;
  3. Update the <option> elements with the array contents in order.

To do that with jQuery, you could do this:

var options = $('select.whatever option');
var arr = options.map(function(_, o) { return { t: $(o).text(), v: o.value }; }).get();
arr.sort(function(o1, o2) { return o1.t > o2.t ? 1 : o1.t < o2.t ? -1 : 0; });
options.each(function(i, o) {
o.value = arr[i].v;
$(o).text(arr[i].t);
});

Here is a working jsfiddle.

edit — If you want to sort such that you ignore alphabetic case, you can use the JavaScript .toUpperCase() or .toLowerCase() functions before comparing:

arr.sort(function(o1, o2) {
var t1 = o1.t.toLowerCase(), t2 = o2.t.toLowerCase();

return t1 > t2 ? 1 : t1 < t2 ? -1 : 0;
});

sort the contents of the list with jquery

You can use a simple sort to achieve the alphabetical sort of your list:

$(document).ready(function() {

var mylist = $('#myUL');

var listitems = mylist.children('li').get();

listitems.sort(function(a, b) {

return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());

})

$.each(listitems, function(idx, itm) {

mylist.append(itm);

});

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="box-content box">

<ul id="myUL">

<li><label class="sf-checked"><input data-keyword="lampmodel-bouwlamp" type="checkbox" name="attribute[357]" value="Bouwlamp" checked="checked">Bouwlamp </label></li>

<li><label><input data-keyword="lampmodel-bouwlamp-werklamp" type="checkbox" name="attribute[357]" value="Werklamp">Werklamp</label></li>

<li><label><input data-keyword="lampmodel-breedstraler-bouwlamp-werklamp" type="checkbox" name="attribute[357]" value="Breedstraler">Breedstraler</label></li>

<li><label><input data-keyword="lampmodel-looplamp-werklamp" type="checkbox" name="attribute[357]" value="Looplamp">Looplamp</label></li>

<li><label><input data-keyword="lampmodel-tl-lamp" type="checkbox" name="attribute[357]" value="TL-lamp">TL-lamp </label></li>

</ul>

</div>

Sort list numerally and then alphabetically using jQuery?

Use this sortEm():

function sortEm(a,b){
var emA = parseInt($('em',a).text().replace(/[\(\)]/g,''));
var emB = parseInt($('em',b).text().replace(/[\(\)]/g,''));
if (emA == emB) { // sort alphabetically if em number are equal
return sortAlpha(a,b);
}
return emA < emB ? 1 : -1;
}

jQuery: how to sort list text taking into account numerical values

Since you have to sort the text where it includes numbers, then do:

return A.localeCompare(B, false, {
numeric: true
})

You can find more information on localCompare and the options here

So you code will look like:

$('ul').children("li").sort(function(a, b) {
var A = $(a).text().toUpperCase();
var B = $(b).text().toUpperCase();
return A.localeCompare(B, false, {
numeric: true
})
}).appendTo('ul');

Demo

$('ul').children("li").sort(function(a, b) {
var A = $(a).text().toUpperCase();
var B = $(b).text().toUpperCase();
return A.localeCompare(B, false, {
numeric: true
})
}).appendTo('ul');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>iPhone 6</li>
<li>iPhone 8</li>
<li>samsung galaxy s8</li>
<li>samsung galaxy s10</li>
<li>iPhone 11</li>
<li>iPhone 12</li>
<li>samsung galaxy s20</li>
</ul>

Sort menu items alphabetically

You can define a helper function sortItems which will sort items in a single list and the invoke it on each list individually (via $('.dropdown-menu').each(sortItems); ).

The sortItems function finds all <a> items, sorts them alphabetically and then reinserts them back into the list in correct order.

function sortItems(index, menu){
const listItems = $(menu).children('a').get();
listItems.sort(function(a, b) {
return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
});
$(menu).append(listItems);
}

$('.dropdown-menu').each(sortItems);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li class=" dropdown">
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item 1" href="/donate_today">Donate</a>
<a class="dropdown-item 2" href="/ways_to_give">Ways To Give</a>
<a class="dropdown-item 2" href="/planned_giving_a_legacy_of_love">Legacy of Love</a>
<a class="dropdown-item 2" href="/paypal">Paypal</a>
</div>
</li>

<li class="dropdown">
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item 1" href="/adopt">Adopt</a>
<a class="dropdown-item 2" href="/adopt_today">Adoption Process</a>
<a class="dropdown-item 2" href="/alumni">Alumni</a>
<a class="dropdown-item 2" href="/adoptable_animals">Adoptable Animals</a>
<a class="dropdown-item 2" href="/resources">Resources</a>
<a class="dropdown-item 2" href="/foster_to_adopt">Foster To Adopt</a>
</div>
</li>

Use jQuery to sort List Items alphabetically - then sort special items Numerically

You need a comparator function, and a way to rearrange the elements. Plugins are available which given the former will do the latter for you, although if the elements are the sole children of a single parent it's pretty easy (see below).

For your comparator, you'll need something which can be given a pair of your <li> elements, and tell you which comes first:

function myCompare(a, b) {
var cls_a = parseInt(a.classList, 10);
var cls_b = parseInt(b.classList, 10);

cls_a = cls_a || -1 ; // make blank class == -1
cls_b = cls_b || -1 ; // ditto

if (cls_a === cls_b) {
var str_a = a.innerText || a.textContent;
var str_b = b.innerText || b.textContent;
return str_a.localeCompare(str_b);
} else {
return cls_a - cls_b; // numeric descending sort
}
}

and for rearranging:

var $el = $('li');
var $ul = $('ul');
$el.sort(myCompare); // from above
$el.each(function() {
$ul.append(this);
});

The .each loop works by just taking each sorted item, and adding it to the end of the <ul> - when there's none left, it's done.

Shorter versions of the above are possible, e.g.:

$('li').sort(myCompare).appendTo($('ul'));

See this jsfiddle



Related Topics



Leave a reply



Submit