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?
Here's a multiple-level sort method. I'm including a snippet from an Angular JS module, but you can accomplish the same thing by scoping the sort keys objects such that your sort function has access to them. You can see the full module at Plunker.
Solution working with different types and with upper and lower cases.
For example, without the
toLowerCase
statement, "Goodyear" will come before "doe" with an ascending sort. Run the code snippet at the bottom of my answer to view the different behaviors.JSON DATA:
JSON Sort Function:
Usage:
Try this on for elegance and efficiency.
jQuery is fine, but it's not ideal for sorting here, unless you don't have the original array handy. 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:
Then:
Play with a working example here.
Demo: http://jsfiddle.net/VAKrE/1019/
Successfully pass equal values (keep same order). Flexible : handle ascendant (123) or descendant (321), works for numbers, letters, and unicodes. Works on all tested devices (Chrome, Android default browser, FF).
Given data such :
Sorting by ascending or reverse order:
If you don't mind using an external library, Lodash has lots of wonderful utilities
You can also sort by multiple properties. Here's a plunk showing it in action