I have an array of dates as below:
var unavailableDates = ["31-5-2014", "1-6-2014", "2-6-2014", "3-6-2014", "26-5-2014", "27-5-2014", "28-5-2014", "29-5-2014"];
How can I sort this array without changing the date format?
I have an array of dates as below:
var unavailableDates = ["31-5-2014", "1-6-2014", "2-6-2014", "3-6-2014", "26-5-2014", "27-5-2014", "28-5-2014", "29-5-2014"];
How can I sort this array without changing the date format?
Code speak for itself.
var unavailableDates = ["31-5-2014", "1-6-2014", "2-6-2014", "3-6-2014", "26-5-2014", "27-5-2014", "28-5-2014", "29-5-2014"];
unavailableDates = unavailableDates
.map(function (val, idx) {
var arr = val.split('-');
return new Date(arr[2], arr[1] - 1, arr[0]);
})
.sort(function (x, y) {
return x > y
});
console.log(unavailableDates);
Hope it would be work for you, try this code
var unavailableDates = ["31-5-2014", "1-6-2014", "2-6-2014",
"3-6-2014", "26-5-2014", "27-5-2014", "28-5-2014", "29-5-2014"];
function SortByDate(a, b){
var amyDate = a.split("-");
var aNewDate=new Date(amyDate[1]+","+amyDate[0]+","+amyDate[2]).getTime();
var bmyDate = b.split("-");
var bNewDate=new Date(bmyDate[1]+","+bmyDate[0]+","+bmyDate[2]).getTime();
return ((aNewDate < bNewDate) ? -1 : ((aNewDate > bNewDate) ? 1 : 0));
}
console.log(unavailableDates.sort(SortByDate));
This alternative should work fine and does not change the date format at all. The sort function uses date format YYYYMMDD
just for sorting only but leaves the original dates intact.
var unavailableDates = ["31-5-2014", "1-6-2014", "2-6-2014", "3-6-2014", "26-5-2014", "27-5-2014", "28-5-2014", "29-5-2014"];
unavailableDates.sort(function( a, b ) {
var sA = a.split( '-' ).map(function(v,i) { return (i<2)?("0"+v).substr(-2):v; }).reverse().join('');
var sB = b.split( '-' ).map(function(v,i) { return (i<2)?("0"+v).substr(-2):v; }).reverse().join('');
return sA > sB;
})
console.log( unavailableDates );
var eventDates = ["31-5-2014", "1-6-2014", "2-6-2014", "3-6-2014", "26-5-2014", "27-5-2014", "28-5-2014", "29-5-2014"];
var result = data.sort(function (a, b){ new Date(a.eventDates).getTime() - new Date(b.eventDates).getTime()
});
console.log(result);