4

I have an Unordered List with me

<ul class="uol">
      <li>beta</li>
      <li>gamma</li>
      <li>alpha</li>
</ul>​​​​​

One of my co-workers (on a long leave) wrote some code that sorts this list.

$(".uol li").sort(asc).appendTo('.uol');

function asc(a, b){
  return ($(b).text()) < ($(a).text());    
}


function desc(a, b){
  return ($(b).text()) > ($(a).text());    
}​

(fiddle)

I am unable to understand what does the code do, especially this line:

$(".uol li").sort(asc).appendTo('.uol');

Can anyone please explain this? Also, is this the best way to sort the UOL or is there a better way you know of?

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
Tom Hodder
  • 101
  • 4
  • That is probably the best way. That line selects the list items, sorts them using the named asc function, and then appends them to the ul. – Kevin B Nov 06 '12 at 15:02
  • You could move away from using the undocumented .sort method to instead use the one on Array, however that will make the code less readable. – Kevin B Nov 06 '12 at 15:04
  • I just wrote a detailed explanation of the `sort()` function for another answer. [You can read it here if you want a deep explanation.](http://stackoverflow.com/questions/3423394/algorithm-of-javascript-sort-function/13171179#13171179) – Aust Nov 06 '12 at 15:05
  • Can you give an example? – Tom Hodder Nov 06 '12 at 15:05
  • ... isn't a really good example included in your question? – Kevin B Nov 06 '12 at 15:08
  • Kevin B, I mean an example using the Array you suggested – Tom Hodder Nov 06 '12 at 15:10
  • @Aust, looks like a real detailed one. I will go through it later during the day – Tom Hodder Nov 06 '12 at 15:11
  • Ah, sorry. here you go, less readable, but uses documented methods. `$( $.makeArray($(".uol li")).sort(asc) ).appendTo(".uol");` – Kevin B Nov 06 '12 at 15:13
  • Thanks Kevin B for your answer. Always good to know multiple ways to approach a problem. Can you also look at http://stackoverflow.com/questions/13254102/adding-filters-to-list – Tom Hodder Nov 06 '12 at 15:23

2 Answers2

2

$(".uol li") this gives the all the li items within the .uol class. .sort(asc) does the sorting in ascending order. .appendTo('.uol') . Appends the result into .uol class container.

kjana83
  • 398
  • 3
  • 16
0

.sort() is a javascript function that sorts an array, using the sorting function you pass it.

the function he chose to pass, checks between two adjacent values which one's text has a lower ascii value. the sorter will continue to run this function between every two adjacent values in the array until it is sorted.

Rodik
  • 4,054
  • 26
  • 49