Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

217
Views
Sorting an array based on times

I have an array of objects containing time stamps and I am attempting to sort them in ascending order. Ive tried converting them to 24 hour time using moment when sorting also comparing the time stamps themselves but for some reason I am still getting my times in a random order. Is there something Im missing?

data when already converted 12 hour time

[{start: '9:04 AM', end: '9:34 AM'}, {start: '3:04 AM', end: '3:34 AM'}...]
const sortedAppointments = appointments.sort(
    (a, b) => moment(a.start).format("H:mm") - moment(b.start).format("H:mm"),
  );

note: I am mapping over the array in the UI after it is sorted. But the output from this sort function is still out of order "/

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Read the times into moment with the correct format, then compare the UNIX timestamps.

const sortedAppointments = appointments.sort(
    (a, b) => moment(a.start, "h:mm a").unix() - moment(b.start, "h:mm a").unix()
);
about 4 years ago · Juan Pablo Isaza Report

0

For what it's worth, here's a version without the 200+kb download of moment.js

let appointments = [{
  start: '9:04 AM',
  end: '9:34 AM'
}, {
  start: '9:04 PM',
  end: '10:34 PM'
}, {
  start: '3:04 AM',
  end: '3:34 AM'
}]
const conv = time => {
  let mer = time.split(" ")[1].toLowerCase(),
    tm = time.split(" ")[0].split(":");
  if (mer === "pm") tm[0] = +tm[0] + 12;
  return +tm.join('');
}
const sortedAppointments = appointments.sort(
  (a, b) => conv(a.start) - conv(b.start)
);

console.log(sortedAppointments)

about 4 years ago · Juan Pablo Isaza Report

0

This is the solution that worked best for me with time in UTC :

const sortedAppointments = appointments.sort(
    (a, b) => moment(a.start).format("x") - moment(b.start).format("x"),
  );
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!