Kemal Emin Kemal Emin - 6 months ago 25
jQuery Question

Sorting JSON by values

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"
}
]
}


Now that this is returned from my server side code, I run
jQuery.each
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 result set. But I want to avoid this and use jQuery to sort the resulting JSON to prevent round trips to the server, and multiple database access.

How can I achieve this using jQuery?

Answer

Try this on for elegance and efficiency.

I love my jQuery, but it's not ideal for sorting here, unless you can only use the existing html (you don't have the array handy to do your sorting on). Just write a function that takes the property name as a string and the order (ascending or descending) as a boolean, write a simple comparison function, and use the native js sort() function. This way you don't have to write a separate sorting function for each property:

var people = [
    {
        "f_name": "john",
        "l_name": "doe",
        "sequence": "0",
        "title" : "president",
        "url" : "google.com",
        "color" : "333333",
    }
    // etc
];

function sortResults(prop, asc) {
    people = people.sort(function(a, b) {
        if (asc) {
            return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);
        } else {
            return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);
        }
    });
    showResults();
}

Then:

sortResults('l_name', true);

Play with a working example here.