Natural sort on JS

You block advertising

Please disable ad blocker

Read more

Sometimes it becomes necessary to sort the list with JS and everything would be alright, but sometimes there is a case where the elements of the list contain text with a numbers, and even a float ones. All this is a natural sorting and now I’ll take a look at how natural sorting on jQuery works with float numbers in a string.

For example, there is a sidebar where the elements of the list are written not by number, but, for example, by creation date (this is a real example from WordPress, where categories are displayed by creation date or id). We have to sort this list by the number in square brackets.

This is html list:

<aside class="sidebar">
    <ul class="elements-list">
        <li class="cat-item">
        	<a>Elements 1</a>
			<ul class="children">
				<li><a href="#">[A1.1] Brand</a></li>
				<li><a href="#">[A2.2] Secondary-Button</a></li>
				<li><a href="#">[A1.3] Fonts</a></li>
				<li><a href="#">[A1.2] Colors</a></li>
				<li><a href="#">[A2.3] Borderless-Button</a></li>
				<li><a href="#">[A2.1] Primary-Button</a></li>
			</ul>
		</li>
		<li class="cat-item">
			<a>Elements 2</a>
			<ul class="children">
				<li><a href="#">[M13.1] Chain Item 1</a></li>
				<li><a href="#">[M13.3] Chain Item 3</a></li>
				<li><a href="#">[M13.2] Chain Item 2</a></li>
				<li><a href="#">[M14.1] Linklists</a></li>
				<li><a href="#">[M13.4] Chain Item 4</a></li>
				<li><a href="#">[M12.1] Contact Form</a></li>
				<li><a href="#">[M13.5] Chain Item 5</a></li>
			</ul>
		</li>
    </ul>
</aside>

To make a natural sort, you need to write a small js code:

$('.elements-list .children').each(function(){
    var mylist = $(this);
    var listitems = mylist.children('li').get();
    listitems.sort(function(a,b) {
        var compA = $(a).text().toUpperCase();
        var compB = $(b).text().toUpperCase();
        return parseFloat(compA.match(/\d+(\.\d)/)[0],10) - parseFloat(compB.match(/\d+(\.\d)/)[0],10);
    })
    $.each(listitems, function(idx, itm) { mylist.append(itm); });
});

As you can see, we take all elements from the child list .children, transform the text from each li in the string and compare each element as float numbers with the help of parseFloat. Actually, the natural sorting on jQuery is not so complicated. Working example can be viewed here.

Demo
You block advertising

Please disable ad blocker

Read more
Comments (0)
Leave a Reply

Your email address will not be published. Required fields are marked *