Click here to Skip to main content
15,879,535 members
Articles / jQuery
Tip/Trick

Sort a JSON Array Programmatically by a Property

Rate me:
Please Sign up or sign in to vote.
4.82/5 (8 votes)
12 Jun 2015CPOL2 min read 25.9K   10   5
This tip shows how to sort a JSON array programmatically by a property.

Introduction

In this tip, 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 thought of sharing that with all of you.

Using the Code

First of all, we will add a jQuery reference as in the following:

JavaScript
<script src="jquery-2.1.4.min.js"></script>  

Now we need some, data right? Please have a look at the following JSON data.

JavaScript
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?

JavaScript
<div id="unsorted"></div>
<div id="sorted"></div>  
<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.

JavaScript
var jsonObject;  
        $(function () {  
            $('#sorted').hide();  
            loadUnsorted();  
            $('#makemesort').click(function () { 
                loadSorted();  
                $('#makemesort').hide();  
                $('#sorted').show();  
            });  
        });  

The following is the function definition for the loadUnsorted() function.

JavaScript
function loadUnsorted() {  
           jsonObject = $.parseJSON(data);  
           var html = '<table><th>Year</th>
           <th>X Value</th><th>Y Value</th>';  
           for (i = 0; i < jsonObject.length; i++) {  
               html += '<tr><td>' + jsonObject[i].name + '</td><td>' + 
               jsonObject[i].data[0].x + '</td><td>' + 
               jsonObject[i].data[0].y + '</td></tr>';  
           }  
           html += '</table>';  
           $('#unsorted').append(html);  
       }  

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:

Image 1

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:

JavaScript
$('#makemesort').click(function () {     
                loadSorted();  
                $('#makemesort').hide();  
                $('#sorted').show();  
              });  

So, here is the definition for the loadSorted() function.

JavaScript
function loadSorted() {  
           jsonObject.sort(SortMe);  
           var html = '<table><th>Year</th>
           <th>X Value</th><th>Y Value</th>';  
           for (i = 0; i < jsonObject.length; i++) {  
               html += '<tr><td>' + jsonObject[i].name + 
               '</td><td>' + 
               jsonObject[i].data[0].x + '</td><td>' + 
               jsonObject[i].data[0].y + '</td></tr>';  
           }  
           html += '</table>';  
           $('#sorted').append(html);  
       }  

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.

JavaScript
function SortMe(a, b) {  
           if (b.name != null && b.name != undefined && a.name != null && a.name != undefined) { 
               var First = a.name.toString().toLowerCase();  
               var Second = b.name.toString().toLowerCase();  
               return ((First < Second) ? -1 : ((First > Second) ? 1 : 0));  
           }  
       }   

What our "sortMe" function does is, it will take two objects at a time and compare those by the property "name" of each object.

JavaScript
(First < Second) ? -1 : ((First > Second) ? 1 : 0)  

Now, shall we look into the complete code? We have done everything folks.

Complete Code

JavaScript
<!DOCTYPE html>  
<html>  
<head>  
    <title>Sort JSON Object by its property and show demo - Sibeesh Passion</title>  
    <script src="jquery-2.1.4.min.js"></script>  
    <style>  
        #unsorted {  
            border: 1px solid #999;  
            width:220px;  
            padding:10px;  
            float:left;  
        }  
        #sorted {  
            border: 1px solid #999;  
            width:220px;  
            padding:10px;  
            float:left;  
        }  
         td {  
            border: 1px solid #ccc;  
            padding: 5px;  
            text-align: center;  
        }  

    </style>  
    <script>    
        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}]}]';  
        var jsonObject;  
        $(function () {  
            $('#sorted').hide();  
            loadUnsorted();  
            $('#makemesort').click(function () { 
                loadSorted();  
                $('#makemesort').hide();  
                $('#sorted').show();  
            });  
        });  

        function loadUnsorted() {  
            jsonObject = $.parseJSON(data);  
            var html = '<table><th>Year</th>
            <th>X Value</th><th>Y Value</th>';  
            for (i = 0; i < jsonObject.length; i++) {  
                html += '<tr><td>' + jsonObject[i].name + 
                '</td><td>' + jsonObject[i].data[0].x + 
                '</td><td>' + jsonObject[i].data[0].y + 
                '</td></tr>';  
            }  
            html += '</table>';  
            $('#unsorted').append(html);  
        }  
        function loadSorted() {  
            jsonObject.sort(SortMe);  
            var html = '<table><th>Year</th>
            <th>X Value</th><th>Y Value</th>';  
            for (i = 0; i < jsonObject.length; i++) {  
                html += '<tr><td>' + jsonObject[i].name + 
                '</td><td>' + jsonObject[i].data[0].x + 
                '</td><td>' + jsonObject[i].data[0].y + '</td></tr>';  
            }  
            html += '</table>';  
            $('#sorted').append(html);  
        }  
        function SortMe(a, b) {  
            if (b.name != null && b.name != undefined && 
            a.name != null && a.name != undefined) { 
                var First = a.name.toString().toLowerCase();  
                var Second = b.name.toString().toLowerCase();  
                return ((First < Second) ? -1 : ((First > Second) ? 1 : 0));  
            }  
        }         
    </script>  
</head>  
<body>  
    <div id="unsorted"></div>  
    <div id="sorted"></div>  
    <button id="makemesort">Make Me Sort</button>  
</body>  
</html>  

So now, it is time to see our output.

Image 2

You can find that 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 tip. Please share your valuable thoughts and comments. Your feedback is always welcome. Thanks in advance. Happy coding!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Germany Germany
I am Sibeesh Venu, an engineer by profession and writer by passion. I’m neither an expert nor a guru. I have been awarded Microsoft MVP 3 times, C# Corner MVP 5 times, DZone MVB. I always love to learn new technologies, and I strongly believe that the one who stops learning is old.

My Blog: Sibeesh Passion
My Website: Sibeesh Venu

Comments and Discussions

 
Questionsort Pin
thewazz18-Jun-15 6:20
professionalthewazz18-Jun-15 6:20 
AnswerRe: sort Pin
Sibeesh Passion18-Jun-15 19:00
professionalSibeesh Passion18-Jun-15 19:00 
GeneralRe: sort Pin
thewazz19-Jun-15 7:03
professionalthewazz19-Jun-15 7:03 
AnswerFormat issues.. Pin
Afzaal Ahmad Zeeshan12-Jun-15 1:43
professionalAfzaal Ahmad Zeeshan12-Jun-15 1:43 
GeneralRe: Format issues.. Pin
Sibeesh Passion12-Jun-15 2:05
professionalSibeesh Passion12-Jun-15 2:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.