How to Sort Custom Objects Array using JQuery

No.of Views1396
Bookmarked1 times
Downloads 
Votes0
By  RRaveen   On  12 Jan 2011 08:01:00
Tag : JQuery , How to
In this article, I will explain how to sort custom objects array using JQuery. Let’s say you have array with custom objects, the custom object has few attributes as well, so in this case, you may need to sort objects with different order with specific attributes.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

In this article, I will explain how to sort custom objects array using JQuery. Let’s say you have array with custom objects, the custom object has few attributes as well, so in this case, you may need to sort objects with different order with specific attributes.

Implementation

As usual create web project and then add JQuery library from Google in to page as like shown below,

Html Code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="objectsortdemo.aspx.cs" Inherits="objectsortdemo" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>How to Sort Objects Array using JQuery</title>

    <script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">  
    </script>
</head>
<body>
    <form id="form1" runat="server" style="font-family: Verdana; font-size: 11px;">
    <div style="font-size: 14px; font-weight: bold;">
        Before sorted
    </div>
    <div id="main1">
    </div>
    <div style="font-size: 14px; font-weight: bold;">
        After sorted
    </div>
    <div id="main2">
    </div>
    </form>
</body>
</html>

Let’s write code create object array and then sort by numeric and string property in objects.

Sort by Numeric attribute

Html Code

<script language="javascript" type="text/javascript">
        $(document).ready(function() {
            var members = [
             { "name": "Dhana", "id": 003, "email": "dhan@gmailcom" },
             { "name": "Abhji", "id": 004, "email": "abji@gmailcom" },
             { "name": "RRaveen", "id": 001, "email": "vrra@gmailcom" },
             { "name": "Jana", "id": 002, "email": "jana@gmailcom" },
             { "name": "John", "id": 005, "email": "john@gmailcom" }
             ];

            $.each(members, function(index, value) {
                $("#main1").append("<p><strong>Id:</strong>" + value.id + "- <strong>Name:</strong>" + value.name + "- <strong>Email:</strong>" + value.email + "</p>");
            })
             ;
            members = members.sort(function(a, b) {           
     return a.id - b.id;
                       });
            $.each(members, function(index, value) {
                $("#main2").append("<p><strong>Id:</strong>" + value.id + "- <strong>Name:</strong>" + value.name + "- <strong>Email:</strong>" + value.email + "</p>");
            });
        });
    </script>

Code Explanation

1.    I have create a array with members object with name, id and email as attributes
2.    Then use the sort method to array  with id(numeric)
3.    Finally print output in within div.

Now run and see the sorted objects like below,

Image Loading

sort by id in asc order

Sort by String attribute

Html code

<script language="javascript" type="text/javascript">
        $(document).ready(function() {
            var members = [
             { "name": "Dhana", "id": 003, "email": "dhan@gmailcom" },
             { "name": "Abhji", "id": 004, "email": "abji@gmailcom" },
             { "name": "RRaveen", "id": 001, "email": "vrra@gmailcom" },
             { "name": "Jana", "id": 002, "email": "jana@gmailcom" },
             { "name": "John", "id": 005, "email": "john@gmailcom" }
             ];

            $.each(members, function(index, value) {
                $("#main1").append("<p><strong>Id:</strong>" + value.id + "- <strong>Name:</strong>" + value.name + "- <strong>Email:</strong>" + value.email + "</p>");
            })
             ;
            members = members.sort(function(a, b) {
                if (a.name < b.name) { return -1 };
                if (a.name > b.name) { return 1 };                
                return 0;
            });
            $.each(members, function(index, value) {
                $("#main2").append("<p><strong>Id:</strong>" + value.id + "- <strong>Name:</strong>" + value.name + "- <strong>Email:</strong>" + value.email + "</p>");
            });
        });
    </script>

In above code, I have used same logic to sort by name as like used for sort by ID, but compare each object name compare is done with additional checking to sort and add again to members array.

Output 

Image Loading

sorted by name in asc order

That's all, now take look live demo for sorting.

Live Demo

Sort custom objects array

Download Sample Code

Download source files -1 kb

Conclusion

In this article, we have learned how to sort custom objects with JQuery by attributes in objects. Sort with numeric and string type as well also included in demonstration. Hopes help and thank you for reading.

 
Sign Up to vote for this article
 
About Author
 
RRaveen
Occupation-Software Engineer
Company-TGS
Member Type-Gold
Location-Singapore
Joined date-03 Jun 2009
Home Page-codegain.com
Blog Page-www.codegain.com
- B.Sc. degree in Computer Science. - 4+ years experience in Visual C#.net and VB.net - Obsessed in OOP style design and programming. - Designing and developing Network security tools. - Designing and developing a client/server application for sharing files among users in a way other than FTP protocol. - Designing and implementing GSM gateway applications and bulk messaging. - Windows Mobile and Symbian Programming - Having knowledge with ERP solutions
 
 
Other popularSectionarticles
    The JQuery is powerful client side JavaScript library. Today I’m going to show you how to create cascading DropDownList using JQuery with JSON in ASP.NET.I hope you are all heard about cascading DropDownList and how to use with AJAX tool kit
    Published Date : 07/Dec/2010
    In this article I will demonstration to how to validate whether to check at least one checkbox is checked in the Gridview in ASP.NET using JQuery. The JQuery is significant library to manipulate client html and css with less line of code.Before Jquery come up we have used the pure JavaScript to implement this features. I will give the JavaScript code as well in end of this article.
    Published Date : 30/Dec/2010
    Today I have implemented to my project to check and uncheck all checkboxes within gridview in asp.net. So in this article we focus how to implement this features using JQuery with less code. And also I have given live demonstration as well you can try it in live.
    Published Date : 29/Dec/2010
    The JQuery is powerful library to manipulate client side HTML, CSS, object and etc. On this article I will explain how to sort element within array using JQuery. In this demonstration I will show sort for string and numeric elements.
    Published Date : 11/Jan/2011
    Today I have introduced the new features for CodeGain article submit page to count characters for description textbox with JQuery on time. The character counter is support to users to display how many characters have entered and how many chars remaining in live.
    Published Date : 25/Dec/2010
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top