Sort a JSON Array Programmatically by a Property

Introduction
 
Hi all, I hope you all are fine. Today we will learn how to sort a JSON object by its property. We will be using normal jQuery features to do this. I hope you will like it.
 
Background
 
Yesterday I got a situation where I needed to sort my JSON object that I am creating using server data. So I though of sharing that with you all.
 
Using the code
 
First of all we will add a jQuery reference as in the following:
  1. <script src="jquery-2.1.4.min.js"></script>  
Now we need some, data right? Please have a look at the following JSON data.
  1. var data = '[{"name":2014,"data":[{"x":"1","y":222808746.81}]},{"name":2013,"data":[{"x":"2","y":289647045.18}]},{"name":2014,"data":[{"x":"2","y":285136890.07}]},{"name":2013,"data":[{"x":"3","y":370853178.74}]},{"name":2014,"data":[{"x":"3","y":403272964.28}]},{"name":2012,"data":[{"x":"4","y":217294031.36}]},{"name":2013,"data":[{"x":"4","y":224715039.94}]},{"name":2014,"data":[{"x":"4","y":249034460.23}]},{"name":2012,"data":[{"x":"5","y":215978054.15}]},{"name":2013,"data":[{"x":"5","y":241211810.92}]}]';  
Next we need some UI elements. Am I right?
  1. <div id="unsorted"></div>  
  2.     <div id="sorted"></div>  
  3.     <button id="makemesort">Make Me Sort</button>  
What next?  We need to show this data to our UI, right? For that I am calling a function in our document ready function.
  1. var jsonObject;  
  2.         $(function () {  
  3.             $('#sorted').hide();  
  4.             loadUnsorted();  
  5.             $('#makemesort').click(function () {                 
  6.                 loadSorted();  
  7.                 $('#makemesort').hide();  
  8.                 $('#sorted').show();  
  9.             });  
  10.         });  
The following is the function definition for the loadUnsorted() function.
  1. function loadUnsorted() {  
  2.            jsonObject = $.parseJSON(data);  
  3.            var html = '<table><th>Year</th><th>X Value</th><th>Y Value</th>';  
  4.            for (i = 0; i < jsonObject.length; i++) {  
  5.                html += '<tr><td>' + jsonObject[i].name + '</td><td>' + jsonObject[i].data[0].x + '</td><td>' + jsonObject[i].data[0].y + '</td></tr>';  
  6.            }  
  7.            html += '</table>';  
  8.            $('#unsorted').append(html);  
  9.        }  
What we are doing here is parsing our data and appending the data to our UI element using a for loop.
  
Now if you run it, you will get output as follows.
 
 
Now we have successfully formatted our data and shown it to our UI.  Cool, right?
 
So shall we go and sort our data? I guess you said "Yes". Awesome.
 
Now we will create a click event for our "Make me sort" button as in the following:
  1. $('#makemesort').click(function () {                 
  2.                 loadSorted();  
  3.                 $('#makemesort').hide();  
  4.                 $('#sorted').show();  
  5.             });  
So here is the definition for the loadSorted() function.
  1. function loadSorted() {  
  2.            jsonObject.sort(SortMe);  
  3.            var html = '<table><th>Year</th><th>X Value</th><th>Y Value</th>';  
  4.            for (i = 0; i < jsonObject.length; i++) {  
  5.                html += '<tr><td>' + jsonObject[i].name + '</td><td>' + jsonObject[i].data[0].x + '</td><td>' + jsonObject[i].data[0].y + '</td></tr>';  
  6.            }  
  7.            html += '</table>';  
  8.            $('#sorted').append(html);  
  9.        }  
Now I guess you could determine the difference of both the loadSorted() and loadUnsorted() functions. Yeah, you are right. I am calling a sort function "sortMe"  there.
  1. function SortMe(a, b) {  
  2.            if (b.name != null && b.name != undefined && a.name != null && a.name != undefined) {  
  3.                var First = a.name.toString().toLowerCase();  
  4.                var Second = b.name.toString().toLowerCase();  
  5.                return ((First < Second) ? -1 : ((First > Second) ? 1 : 0));  
  6.            }  
  7.        }   
What our "sortMe" function does is, it will take two objects at a time and compare those by the property "name" of each object.
  1. (First < Second) ? -1 : ((First > Second) ? 1 : 0)  
Now shall we look into the complete code? We have done everything folks.
 
Complete Code
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title>Sort JSON Object by its property and show demo - Sibeesh Passion</title>  
  5.     <script src="jquery-2.1.4.min.js"></script>  
  6.     <style>  
  7.         #unsorted {  
  8.             border: 1px solid #999;  
  9.             width:220px;  
  10.             padding:10px;  
  11.             float:left;  
  12.         }  
  13.         #sorted {  
  14.             border: 1px solid #999;  
  15.             width:220px;  
  16.             padding:10px;  
  17.             float:left;  
  18.         }  
  19.          td {  
  20.             border: 1px solid #ccc;  
  21.             padding: 5px;  
  22.             text-align: center;  
  23.         }  
  24.   
  25.     </style>  
  26.     <script>    
  27.         var data = '[{"name":2014,"data":[{"x":"1","y":222808746.81}]},{"name":2013,"data":[{"x":"2","y":289647045.18}]},{"name":2014,"data":[{"x":"2","y":285136890.07}]},{"name":2013,"data":[{"x":"3","y":370853178.74}]},{"name":2014,"data":[{"x":"3","y":403272964.28}]},{"name":2012,"data":[{"x":"4","y":217294031.36}]},{"name":2013,"data":[{"x":"4","y":224715039.94}]},{"name":2014,"data":[{"x":"4","y":249034460.23}]},{"name":2012,"data":[{"x":"5","y":215978054.15}]},{"name":2013,"data":[{"x":"5","y":241211810.92}]}]';  
  28.         var jsonObject;  
  29.         $(function () {  
  30.             $('#sorted').hide();  
  31.             loadUnsorted();  
  32.             $('#makemesort').click(function () {                 
  33.                 loadSorted();  
  34.                 $('#makemesort').hide();  
  35.                 $('#sorted').show();  
  36.             });  
  37.         });  
  38.         function loadUnsorted() {  
  39.             jsonObject = $.parseJSON(data);  
  40.             var html = '<table><th>Year</th><th>X Value</th><th>Y Value</th>';  
  41.             for (i = 0; i < jsonObject.length; i++) {  
  42.                 html += '<tr><td>' + jsonObject[i].name + '</td><td>' + jsonObject[i].data[0].x + '</td><td>' + jsonObject[i].data[0].y + '</td></tr>';  
  43.             }  
  44.             html += '</table>';  
  45.             $('#unsorted').append(html);  
  46.         }  
  47.         function loadSorted() {  
  48.             jsonObject.sort(SortMe);  
  49.             var html = '<table><th>Year</th><th>X Value</th><th>Y Value</th>';  
  50.             for (i = 0; i < jsonObject.length; i++) {  
  51.                 html += '<tr><td>' + jsonObject[i].name + '</td><td>' + jsonObject[i].data[0].x + '</td><td>' + jsonObject[i].data[0].y + '</td></tr>';  
  52.             }  
  53.             html += '</table>';  
  54.             $('#sorted').append(html);  
  55.         }  
  56.         function SortMe(a, b) {  
  57.             if (b.name != null && b.name != undefined && a.name != null && a.name != undefined) {  
  58.                 var First = a.name.toString().toLowerCase();  
  59.                 var Second = b.name.toString().toLowerCase();  
  60.                 return ((First < Second) ? -1 : ((First > Second) ? 1 : 0));  
  61.             }  
  62.         }         
  63.     </script>  
  64. </head>  
  65. <body>  
  66.     <div id="unsorted"></div>  
  67.     <div id="sorted"></div>  
  68.     <button id="makemesort">Make Me Sort</button>  
  69. </body>  
  70. </html>  
So now it is time to see our output. I am eager to see it.
 
 
 You can find we have sorted our object and shown it in a separate table. Cool.
 
That is all for the day. I will return with another article soon.
 
Conclusion
 
I hope you liked this article. Please share me your valuable thoughts and comments. Your feedbacks are always welcome. Thanks in advance. Happy coding!.
 
Kindest Regards.

Up Next
    Ebook Download
    View all
    Learn
    View all