I have a JSON object in JavaScript and I am trying to sort the object in order by dates.
fileListObj[id] = date;
output : "#HIDDEN ID": "16/12/2013"
How can I sort the object to be in order by most recent date?
I only know how to do this in php
I have a JSON object in JavaScript and I am trying to sort the object in order by dates.
fileListObj[id] = date;
output : "#HIDDEN ID": "16/12/2013"
How can I sort the object to be in order by most recent date?
I only know how to do this in php
First you'll want to write/get a date parser. Using Javascript's native Date object is unreliable for parsing raw strings.
Then you'll want to use Array.prototype.sort():
function parseDate(input) {
var parts = input.split('/');
return new Date(parts[2], parts[1]-1, parts[0]);
}
function sortAsc(a,b)
{ return parseDate(a.date) > parseDate(b.date); }
function sortDesc(a,b)
{ return parseDate(a.date) < parseDate(b.date); }
list.sort(sortAsc);
Here's a working example, the sorted table will contain ISO format dates
var dates = ["12/05/2012", "09/06/2011","09/11/2012"]
var sorted=[];
for(var i=0, i= dates.length;i++){
var p = dates[i].split(/\D+/g);
sorted[i]= new Date(p[2],p[1],p[0]);
}
alert(sorted.sort(function(a,b){return b-a}).join("\n"));
To get the same input format you can use this function:
function formatDate(d)
{
date = new Date(d)
var dd = date.getDate();
var mm = date.getMonth()+1;
var yyyy = date.getFullYear();
if(dd<10){dd='0'+dd}
if(mm<10){mm='0'+mm};
return d = dd+'/'+mm+'/'+yyyy
}
sorted.sort(function(a,b){return b-a})
formatSorted = []
for(var i=0; i<sorted.length; i++)
{
formatSorted.push(formatDate(sorted[i]))
}
alert(formatSorted.join("\n"));