Sort string array containing time in format '09:00 AM'?
Try this
var times = ['01:00 am', '06:00 pm', '12:00 pm', '03:00 am', '12:00 am'];
times.sort(function (a, b) {
return new Date('1970/01/01 ' + a) - new Date('1970/01/01 ' + b);
});
console.log(times);
My solution (For times formated like "11:00", "16:30"..)
sortTimes: function (array) {
return array.sort(function (a, b) {
if (parseInt(a.split(":")[0]) - parseInt(b.split(":")[0]) === 0) {
return parseInt(a.split(":")[1]) - parseInt(b.split(":")[1]);
} else {
return parseInt(a.split(":")[0]) - parseInt(b.split(":")[0]);
}
})
}
In case someone wanted to know haha
Implement the sort(compare) function and compare the date string using any arbitrary date :
Array.sort(function (a, b) {
return Date.parse('01/01/2013 '+a) - Date.parse('01/01/2013 '+b)
});
01/01/2013 is any arbitrary date.