tags:

views:

1963

answers:

2

I have a very simple json object like the following:

({
"people": [
{
"f_name": "john",
"l_name": "doe",
"sequence": "0",
"title" : "president",
"url" : "google.com",
"color" : "333333",
},
{
"f_name": "michael",
"l_name": "goodyear",
"sequence": "0",
"title" : "general manager",
"url" : "google.com",
"color" : "333333",
}]
})

Of course there are more records but I kept it to two records for the purpose of keeping things simple.

Now that this is returned from my server side code, I run a jquery.each function to form the necessary html and output the result.

Right now what I am doing is sending an ajax call to the server containing my sort info .. e.g. "Title DESC" and re-run an sql query to return the new resultset. But I want to avoid this and use jquery to sort the resulting json to prevent server roundtrips and multiple database access.

how can I achieve this using jquery?

+2  A: 

You might want to try a variation of this:

http://www.wrichards.com/blog/2009/02/jquery-sorting-elements/

Tahir Akhtar
+2  A: 
jQuery.fn.sort = function() {  
    return this.pushStack( [].sort.apply( this, arguments ), []);  
};  

 function sortLastName(a,b){  
     if (a.l_name == b.l_name){
       return 0;
     }
     return a.l_name> b.l_name ? 1 : -1;  
 };  
  function sortLastNameDesc(a,b){  
     return sortLastName(a,b) * -1;  
 };
var people= [
{
"f_name": "john",
"l_name": "doe",
"sequence": "0",
"title" : "president",
"url" : "google.com",
"color" : "333333",
},
{
"f_name": "michael",
"l_name": "goodyear",
"sequence": "0",
"title" : "general manager",
"url" : "google.com",
"color" : "333333",
}]

sorted=$(people).sort(sortLastNameDesc);
Tahir Akhtar
See my adaptation of Bill Richards code. It's sorting json array based on last name in descending order.The sort callback can be generalized by passing the field name in constructor of function.
Tahir Akhtar
You have to replace innerHTML with l_name in sortLastName
Magnar
Thanks Magnar. I have edited the answer.
Tahir Akhtar
Just to clarify, my first comment, what I mean is that this code can be further modified to support generic sorting.
Tahir Akhtar
Shouldn't sortLastName() return 0 if a.l_name and b.l_name are equal? Perhaps because of the data, it is unnecessary in this case, but reading the code, I can't help thinking of this: http://blogs.msdn.com/oldnewthing/archive/2009/05/08/9595334.aspx ... "First of all, your first comparison function clearly violates the requirements for being a comparison function: It must return zero if the two items compare equal."
Grant Wagner
Yes you are right. It should return 0 when both are equal. As I said it was a quick adaptation of code found elsewhere. Purpose was just to show the concept so I didn't look closely enough.
Tahir Akhtar