Thursday, 11 July 2013

JSON object Sorted by Date

Hi,

Many of them asking how to sort my json objects based on date. And writing many lines of code, sometimes get tired to sort the json object. Here I found simple function to sort your json object based on date.

Not only date you can sort json object based on any attribute by writing custom sort function in your code.

Let me explain how to create custom sort function in java script.

You can download the sample app source code from git repository Sort Json by Date

Example JSON object:
 
var latestOffers=[
          {id: '1', date: '20 Dec 2012, 8:00 am', text:'item1'},
          {id: '2',  date: '29 Jun 2012, 5:47 pm', text:'item2'},
          {id: '3', date: '15 May 2013, 6:40 pm', text:'item3'}         
        ]; 

Now I write sortbydate() function


function sortbydate(a, b) {
    // change the < condition to > for reverse the sort.
    // here you can add your own sorting condition 
    // eg,   return a.id < b.id;   //its sort your object based on id.
    return new Date(a.date).getTime() < new Date(b.date).getTime();
}

Now you can call the Array.sort() with your sortbydate function.


 
latestOffers.sort(sortbydate);
Ti.API.info('sorted json array ==='+ JSON.stringify(latestOffers));


Thanks