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"]