Skip to content

Instantly share code, notes, and snippets.

@atifaziz

atifaziz/sorting.js

Last active May 28, 2020
Embed
What would you like to do?
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