Sort string array containing time in format '09:00 AM'?

后端 未结 5 918
面向向阳花
面向向阳花 2020-12-17 09:45

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

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-17 10:23

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

提交回复
热议问题