1. Computing
Send to a Friend via Email

Date Array Sort

Join the Discussion

Questions? Comments?

An array where each entry starts with a date can be easily sorted provided that the dates are in year, month, day order since with this arrangement the order in which the dates will occur corresponds to the normal dictionary sort sequence applied when you sort any ordinary text entries in an array. When the dates are in day, month, year or month, day, year sorting the array is not so simple because the date sequence no longer corresponds to the natural array sort order. We can of course solve this problem by creating our own custom compare functions.

var dateRE = /^(\d{2})[\/\- ](\d{2})[\/\- ](\d{4})/;
function dmyOrdA(a, b){
a = a.replace(dateRE,"$3$2$1");
b = b.replace(dateRE,"$3$2$1");
if (a>b) return 1;
if (a <b) return -1;
return 0; }
function dmyOrdD(a, b){
a = a.replace(dateRE,"$3$2$1");
b = b.replace(dateRE,"$3$2$1");
if (a>b) return -1;
if (a <b) return 1;
return 0; }
function mdyOrdA(a, b){
a = a.replace(dateRE,"$3$1$2");
b = b.replace(dateRE,"$3$1$2");
if (a>b) return 1;
if (a <b) return -1;
return 0; }
function mdyOrdD(a, b){
a = a.replace(dateRE,"$3$1$2");
b = b.replace(dateRE,"$3$1$2");
if (a>b) return -1;
if (a <b) return 1;
return 0; }

We can now sort any array containing dates by selecting the appropriate compare function that matches the order of the content of the date field and whether we want to sort into ascending or descending order.

If our dates are "dd/mm/ccyy" or "dd-mm-ccyy" or "dd mm ccyy" and we want to sort into ascending order by date we use dmyOrdA or for descending order dmyOrdD. If our dates are "mm/dd/ccyy" or "mm-dd-ccyy" or "mm dd ccyy" we would use mdyOrdA for ascending or mdyOrdD for descending.

Here is an example:

dateArray = new Array('15/10/2000','28/05/1999',
'17/09/2005','06/12/2004','02/01/1998');
dateArray.sort( dmyOrdA );
document.write('Ascending : ' + dateArray + '<br />');
Related Video
Microsoft Excel Sort Feature
Upload Videos to Google Video

©2014 About.com. All rights reserved.