Click here to Skip to main content
11,573,935 members (61,675 online)
Click here to Skip to main content

Sort a JSON Array Programmatically by a Property

, 16 Jun 2015 CPOL 1.7K 4
Rate this:
Please Sign up or sign in to vote.
Sort a JSON Array Programmatically by a Property

Introduction

In this post, 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 had 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:

<script src=&ldquo;jquery-2.1.4.min.js&rdquo;></script>

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

var data = &lsquo;[{&ldquo;name&rdquo;:2014,&rdquo;data&rdquo;:[{&ldquo;x&rdquo;:&rdquo;1&Prime;,&rdquo;y&rdquo;:222808746.81}]},
{&ldquo;name&rdquo;:2013,&rdquo;data&rdquo;:[{&ldquo;x&rdquo;:&rdquo;2&Prime;,&rdquo;y&rdquo;:289647045.18}]},
{&ldquo;name&rdquo;:2014,&rdquo;data&rdquo;:[{&ldquo;x&rdquo;:&rdquo;2&Prime;,&rdquo;y&rdquo;:285136890.07}]},
{&ldquo;name&rdquo;:2013,&rdquo;data&rdquo;:[{&ldquo;x&rdquo;:&rdquo;3&Prime;,&rdquo;y&rdquo;:370853178.74}]},
{&ldquo;name&rdquo;:2014,&rdquo;data&rdquo;:[{&ldquo;x&rdquo;:&rdquo;3&Prime;,&rdquo;y&rdquo;:403272964.28}]},
{&ldquo;name&rdquo;:2012,&rdquo;data&rdquo;:[{&ldquo;x&rdquo;:&rdquo;4&Prime;,&rdquo;y&rdquo;:217294031.36}]},
{&ldquo;name&rdquo;:2013,&rdquo;data&rdquo;:[{&ldquo;x&rdquo;:&rdquo;4&Prime;,&rdquo;y&rdquo;:224715039.94}]},
{&ldquo;name&rdquo;:2014,&rdquo;data&rdquo;:[{&ldquo;x&rdquo;:&rdquo;4&Prime;,&rdquo;y&rdquo;:249034460.23}]},
{&ldquo;name&rdquo;:2012,&rdquo;data&rdquo;:[{&ldquo;x&rdquo;:&rdquo;5&Prime;,&rdquo;y&rdquo;:215978054.15}]},
{&ldquo;name&rdquo;:2013,&rdquo;data&rdquo;:[{&ldquo;x&rdquo;:&rdquo;5&Prime;,&rdquo;y&rdquo;:241211810.92}]}]&rsquo;;

Next, we need some UI elements. Am I right?

<div id=&ldquo;unsorted&rdquo;></div>
    <div id=&ldquo;sorted&rdquo;></div>
    <button id=&ldquo;makemesort&rdquo;>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.

var jsonObject;
        $(function () {
            $(&lsquo;#sorted&rsquo;).hide();
            loadUnsorted();
            $(&lsquo;#makemesort&rsquo;).click(function () {
                loadSorted();
                $(&lsquo;#makemesort&rsquo;).hide();
                $(&lsquo;#sorted&rsquo;).show();
            });
        });

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

function loadUnsorted() {
           jsonObject = $.parseJSON(data);
           var html = &lsquo;<table><th>Year</th>
           <th>X Value</th><th>Y Value</th>&rsquo;;
           for (i = 0; i < jsonObject.length; i++) {
               html += &lsquo;<tr><td>&rsquo; + jsonObject[i].name + 
               &lsquo;</td><td>&rsquo; + 
               jsonObject[i].data[0].x + &lsquo;</td><td>&rsquo; + 
               jsonObject[i].data[0].y + &lsquo;</td></tr>&rsquo;;
           }
           html += &lsquo;</table>&rsquo;;
           $(&lsquo;#unsorted&rsquo;).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:

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:

$(&lsquo;#makemesort&rsquo;).click(function () {
                loadSorted();
                $(&lsquo;#makemesort&rsquo;).hide();
                $(&lsquo;#sorted&rsquo;).show();
            });

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

function loadSorted() {
           jsonObject.sort(SortMe);
           var html = &lsquo;<table><th>Year</th>
           <th>X Value</th><th>Y Value</th>&rsquo;;
           for (i = 0; i < jsonObject.length; i++) {
               html += &lsquo;<tr><td>&rsquo; + jsonObject[i].name + 
               &lsquo;</td><td>&rsquo; + jsonObject[i].data[0].x + 
               &lsquo;</td><td>&rsquo; + jsonObject[i].data[0].y + 
               &lsquo;</td></tr>&rsquo;;
           }
           html += &lsquo;</table>&rsquo;;
           $(&lsquo;#sorted&rsquo;).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.

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.

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

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

Complete Code

<!DOCTYPE html>
<html>
<head>
    <title>Sort JSON Object by its property and show demo &ndash; Sibeesh Passion</title>
    <script src=&ldquo;jquery-2.1.4.min.js&rdquo;></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 = &lsquo;[{&ldquo;name&rdquo;:2014,&rdquo;data&rdquo;:[{&ldquo;x&rdquo;:&rdquo;1&Prime;,&rdquo;y&rdquo;:222808746.81}]},
                   {&ldquo;name&rdquo;:2013,&rdquo;data&rdquo;:[{&ldquo;x&rdquo;:&rdquo;2&Prime;,&rdquo;y&rdquo;:289647045.18}]},
                   {&ldquo;name&rdquo;:2014,&rdquo;data&rdquo;:[{&ldquo;x&rdquo;:&rdquo;2&Prime;,&rdquo;y&rdquo;:285136890.07}]},
                   {&ldquo;name&rdquo;:2013,&rdquo;data&rdquo;:[{&ldquo;x&rdquo;:&rdquo;3&Prime;,&rdquo;y&rdquo;:370853178.74}]},
                   {&ldquo;name&rdquo;:2014,&rdquo;data&rdquo;:[{&ldquo;x&rdquo;:&rdquo;3&Prime;,&rdquo;y&rdquo;:403272964.28}]},
                   {&ldquo;name&rdquo;:2012,&rdquo;data&rdquo;:[{&ldquo;x&rdquo;:&rdquo;4&Prime;,&rdquo;y&rdquo;:217294031.36}]},
                   {&ldquo;name&rdquo;:2013,&rdquo;data&rdquo;:[{&ldquo;x&rdquo;:&rdquo;4&Prime;,&rdquo;y&rdquo;:224715039.94}]},
                   {&ldquo;name&rdquo;:2014,&rdquo;data&rdquo;:[{&ldquo;x&rdquo;:&rdquo;4&Prime;,&rdquo;y&rdquo;:249034460.23}]},
                   {&ldquo;name&rdquo;:2012,&rdquo;data&rdquo;:[{&ldquo;x&rdquo;:&rdquo;5&Prime;,&rdquo;y&rdquo;:215978054.15}]},
                   {&ldquo;name&rdquo;:2013,&rdquo;data&rdquo;:[{&ldquo;x&rdquo;:&rdquo;5&Prime;,&rdquo;y&rdquo;:241211810.92}]}]&rsquo;;
        var jsonObject;
        $(function () {
            $(&lsquo;#sorted&rsquo;).hide();
            loadUnsorted();
            $(&lsquo;#makemesort&rsquo;).click(function () {
                loadSorted();
                $(&lsquo;#makemesort&rsquo;).hide();
                $(&lsquo;#sorted&rsquo;).show();
            });
        });
        function loadUnsorted() {
            jsonObject = $.parseJSON(data);
            var html = &lsquo;<table><th>Year</th>
            <th>X Value</th><th>Y Value</th>&rsquo;;
            for (i = 0; i < jsonObject.length; i++) {
                html += &lsquo;<tr><td>&rsquo; + jsonObject[i].name + 
                &lsquo;</td><td>&rsquo; + 
                jsonObject[i].data[0].x + &lsquo;</td><td>&rsquo; + 
                jsonObject[i].data[0].y + &lsquo;</td></tr>&rsquo;;
            }
            html += &lsquo;</table>&rsquo;;
            $(&lsquo;#unsorted&rsquo;).append(html);
        }
        function loadSorted() {
            jsonObject.sort(SortMe);
            var html = &lsquo;<table><th>Year</th>
            <th>X Value</th><th>Y Value</th>&rsquo;;
            for (i = 0; i < jsonObject.length; i++) {
                html += &lsquo;<tr><td>&rsquo; + 
                jsonObject[i].name + &lsquo;</td><td>&rsquo; + 
                jsonObject[i].data[0].x + &lsquo;</td><td>&rsquo; + 
                jsonObject[i].data[0].y + &lsquo;</td></tr>&rsquo;;
            }
            html += &lsquo;</table>&rsquo;;
            $(&lsquo;#sorted&rsquo;).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=&ldquo;unsorted&rdquo;></div>
    <div id=&ldquo;sorted&rdquo;></div>
    <button id=&ldquo;makemesort&rdquo;>Make Me Sort</button>
</body>
</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 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)

Share

About the Author

Sibeesh Passion
Software Developer
India India

My Blog

Sibeesh|Passion

Other Accounts

@GitHub || @JsFiddle ||@C-Sharp Corner ||@ASP.NET ||@Code Project

Achievements

  • Microsoft ASP.NET Community Article Of The Day - Jun 03, 2015
  • May 2015 Month Winner In C# Corner
  • DZone MVB
  • April 2015 Month Winner In C# Corner
  • Asp.Net Community Article of the Day Sunday, April 26, 2015
  • Ranked 1st in Jan Month Winners in C# Corner
  • Asp.Net Community Article of the Day Sunday January 11 ,2015
  • December 2014 Month Winner In C# Corner
  • C# Corner,2014 MVP
  • October 2014 Month Winners Announced
  • Asp.Net Community Article of the Day November 10th,2014
  • Asp.Net Community Article of the Day Tuesday, December 30, 2014

My Achievements


You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 5 Pin
Mahsa Hassankashi19-Jun-15 10:15
mvpMahsa Hassankashi19-Jun-15 10:15 
GeneralRe: My vote of 5 Pin
Sibeesh Passion19-Jun-15 16:39
professionalSibeesh Passion19-Jun-15 16:39 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150624.2 | Last Updated 16 Jun 2015
Article Copyright 2015 by Sibeesh Passion
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid