Pantsland

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:

  1. Put the existing items in the list into an array
  2. Push the new item into the list
  3. Re-sort the list, then work out where the new item ended up
  4. Insert the item into the document at that position

The code I ended up with looked a little like this:

  1. var newItem = "Item to insert";
  2.  
  3. // Grab all the existing items
  4. var sortedList = new Array();
  5. $(‘#list li’).each(function(i, item) {
  6.         sortedList.push($(this).html().toLowerCase());
  7. })
  8. var initialLength = sortedList.length;
  9.  
  10. // Add the new item and sort the list
  11. sortedList.push(newItem.toLowerCase());
  12. sortedList.sort();
  13.  
  14. // Then find where the item ended up
  15. var i = $.inArray(newItem.toLowerCase(), sortedList);
  16.  
  17. // If the item ends up at the end of the list, just append it
  18. if(i == initialLength) {
  19.         $(‘#contacts-list’).append("
  20.                 <li>" + newItem + "</li>
  21.         ");
  22. // Otherwise, insert it before the element it’s replacing
  23. } else {
  24.         $($(‘#list’).children("li")[i]).before("
  25.                 <li>" + newItem + "</li>
  26.         ");
  27. }

Obviously, there are some inefficiencies in the code, but it’s something pretty good to start with to adapt to your needs.

Leave a Reply

Twitter

  • And the inline comments on sections of the document are even more useful 11:15am
  • iWork.com is cool, would be nice to edit online too, but being able to download in multiple formats is very useful. 11:13am
  • Seriously, why does the new Skype beta have non-standard toolbar icons? It looks like nothing else on the mac. 10:31am
  • @danielbru yeah, SS at MacWorld is so-so, go at something like CES or MWC, usually better than the floor 9:41pm
  • @danielbru the hot tip is to do the press events like ShowStoppers, far more efficient. 9:34pm
  • I still own a car back in Australia, is there any car sharing place I could list it on so I could make some money off that? 8:59pm