Skip to content

Instantly share code, notes, and snippets.

@atifaziz
Last active May 28, 2020 12:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atifaziz/e1a97fafecd3f90e88ec35d54b97edca to your computer and use it in GitHub Desktop.
Save atifaziz/e1a97fafecd3f90e88ec35d54b97edca to your computer and use it in GitHub Desktop.
Two techniques demonstrating sorting time strings
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