Sorting JSON by values
jquery, json
Solution
jQuery isn't particularly helpful for sorting, but here's an elegant and efficient solution. Just write a plain JS function that takes the property name and the order (ascending or descending) and calls the native sort() method with a simple comparison function:
var people = [
{
"f_name": "john",
"l_name": "doe",
"sequence": "0",
"title" : "president",
"url" : "google.com",
"color" : "333333",
}
// etc
];
function sortResults(prop, asc) {
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);
}
});
renderResults();
}
Then:
sortResults('l_name', true);
Play with a working example here.
Problem
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?