Sep 21, 2008
Inserting Items in a Sorted List with jQuery
I hit an interesting problem the other day - take a list of sorted items (in this case, an ordered list of names) and insert a new item in the correct position in the list with Javascript, preserving the sort order. It turns out that this isn’t so hard to do with the help of a little jQuery (and almost as easy without it).
The problem breaks down to:
- Put the existing items in the list into an array
- Push the new item into the list
- Re-sort the list, then work out where the new item ended up
- Insert the item into the document at that position
The code I ended up with looked a little like this:
-
var newItem = "Item to insert";
-
-
// Grab all the existing items
-
var sortedList = new Array();
-
$(‘#list li’).each(function(i, item) {
-
sortedList.push($(this).html().toLowerCase());
-
})
-
var initialLength = sortedList.length;
-
-
// Add the new item and sort the list
-
sortedList.push(newItem.toLowerCase());
-
sortedList.sort();
-
-
// Then find where the item ended up
-
var i = $.inArray(newItem.toLowerCase(), sortedList);
-
-
// If the item ends up at the end of the list, just append it
-
if(i == initialLength) {
-
$(‘#contacts-list’).append("
-
<li>" + newItem + "</li>
-
");
-
// Otherwise, insert it before the element it’s replacing
-
} else {
-
$($(‘#list’).children("li")[i]).before("
-
<li>" + newItem + "</li>
-
");
-
}
Obviously, there are some inefficiencies in the code, but it’s something pretty good to start with to adapt to your needs.