• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

187
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 3 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 3 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 3 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 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error