I am trying to sort my array.
The array consists of data in time format.
Array:
\'9:15 AM\', \'10:20 AM\', \'02:15 PM\'
How
function sortTimes(arrayOfTimes) {
return arrayOfTimes.sort((a, b) => {
const aParts = getNumericParts(a);
const bParts = getNumericParts(b);
// Sorts by hour then minute
return aParts[0] - bParts[0] || aParts[1] - bParts[1];
});
function getNumericParts(time) {
// accounts formats of 9:15 AM and 09:15:30 but does not handle AM/PM in comparison
return time.split(' ')[0].split(':').map(x => +x);
}
}
Here's a more concise and performant variation of Dustin Silk's answer. It takes into account formats of 9:15 AM, 09:15, and 09:15:30 though it does not sort based on seconds. You could add that by using || aParts[2] - bParts[2]
as a part of the return statement.
sortTimes(['08:00', '09:00', '05:00', '08:15', '08:00'])
// Output ["05:00", "08:00", "08:00", "08:15", "09:00"]
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.
var a = ['9:15 AM', '10:20 AM', '02:15 PM'];
var sort = function(a){
var sa = [],
d = new Date(),
ds = d.toDateString();
for(var i = 0; i < a.length; i++){
d = new Date(ds + ' ' + a[i]);
sa.push(d);
}
sa.sort(function(a, b){return a.getTime() - b.getTime();})
return sa;
}