Last active
May 28, 2020 12:54
-
-
Save atifaziz/e1a97fafecd3f90e88ec35d54b97edca to your computer and use it in GitHub Desktop.
Two techniques demonstrating sorting time strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
times = [ '12:00', '10:00', '12:15', '09:30' ] | |
// simple way | |
// relies on string comparison operators (`<` and `>`) | |
sorted = [...times].sort((a, b) => a > b ? 1 : a < b ? -1 : 0) | |
// sorted = [ '09:30', '10:00', '12:00', '12:15' ] | |
// complicated way | |
// - split time on ":" into two parts: hours and minutes | |
// - convert hours and minutes to total minutes (hours * 24 + minutes) | |
// - compare minutes through integer arithmetic | |
// - extract back the original time that was retained throughout | |
sorted = [...times].map(t => [t, t.split(':', 2)]) | |
.map(([t, [h, m]]) => ({ t, m: +h * 60 + +m })) | |
.sort((a, b) => a.m - b.m) | |
.map(({ t }) => t) | |
// sorted = [ '09:30', '10:00', '12:00', '12:15' ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment