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?
JSON (JavaScript Object Notation) is simply data organized in a specific fashion. That fashion mimics the syntax of Object Literals in JavaScript. Data organized in JSON format is used by lanugages other than JavaScript as well. Think of this Data formatting as a new standard of organizing data to send over the web.
Yes, the order of elements in JSON arrays is preserved. From RFC 7159 -The JavaScript Object Notation (JSON) Data Interchange Format (emphasis mine): An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.
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.
Demo: https://jsfiddle.net/kvxazhso/
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 :
var people = [ { 'myKey': 'A', 'status': 0 }, { 'myKey': 'B', 'status': 3 }, { 'myKey': 'C', 'status': 3 }, { 'myKey': 'D', 'status': 2 }, { 'myKey': 'E', 'status': 7 }, ... ];
Sorting by ascending or reverse order:
function sortJSON(arr, key, way) { return arr.sort(function(a, b) { var x = a[key]; var y = b[key]; if (way === '123') { return ((x < y) ? -1 : ((x > y) ? 1 : 0)); } if (way === '321') { return ((x > y) ? -1 : ((x < y) ? 1 : 0)); } }); } people2 = sortJSON(people,'status', '321'); // 123 or 321 alert("2. After processing (0 to x if 123; x to 0 if 321): "+JSON.stringify(people2));
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);
If you don't mind using an external library, Lodash has lots of wonderful utilities
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"
}
];
var sorted = _.sortBy(people, "l_name")
You can also sort by multiple properties. Here's a plunk showing it in action
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With