简体   繁体   中英

Javascript sort dates in array by year DESC, then month ASC, then day ASC

I have an array of classes and the dates they were offered coming back from an AJAX to PHP call. It's returned as 'data' so we'll just call our array data:

var data = [{
  "course": "First Aid",
  "courseDate": "2016-04-25T00:00:00-06:00"
}, {
  "course": "CPR",
  "courseDate": "2016-04-06T00:00:00-06:00"
}, {
  "course": "ASL1",
  "courseDate": "2016-01-07T00:00:00-06:00"
}, {
  "course": "ASL2",
  "courseDate": "2016-03-25T00:00:00-06:00"
},
...etc...
];

I need to be able to display them sorted by date descending. I'm using this simple function:

data.sort(function(a, b) {
   a = new Date(a.courseDate);
   b = new Date(b.courseDate);
   return a > b ? -1 : a < b ? 1 : 0;
});

$.each(data, function(key, val) {
   $('#courseHist').append('<br />' + val.course+' - '+val.courseDate);
});

As expected, I'm getting a return of

1st Aid - 2016-04-25...
CPR - 2016-04-06...
ASL2 - 2016-03-25...
ASL1 - 2015-12-07...

Which is, technically, sorted by date descending. However, I need the return to sort by year descending, then month ascending, then date ascending. Like this:

ASL2 - 2016-03-25...
CPR - 2016-04-06...
1st Aid - 2016-04-25...
ASL1 - 2015-12-07...

I know I need to break my date return up into chunks and arrange from there but I just can't wrap my head around how to do that. Any help is greatly appreciated!

Alternately, I could do it on the PHP side if anyone has a solution for that.

I have a fiddle HERE if you want to mess with it. - updated with working code from user blex

Yo can split the data and sort it independently by year desc, month asc and day asc.

 var data = [{ "course": "First Aid", "courseDate": "2016-04-25T00:00:00-06:00" }, { "course": "CPR", "courseDate": "2016-04-06T00:00:00-06:00" }, { "course": "ASL1", "courseDate": "2016-01-07T00:00:00-06:00" }, { "course": "ASL2", "courseDate": "2016-03-25T00:00:00-06:00" }, { "course": "ASL2X", "courseDate": "2015-03-25T00:00:00-06:00" }]; data.sort(function (a, b) { var aa = a.courseDate.split(/\\D/), bb = b.courseDate.split(/\\D/); return bb[0] - aa[0] || aa[1] - bb[1] || aa[2] - bb[2]; }); document.write('<pre>' + JSON.stringify(data, 0, 4) + '</pre>'); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM