CourtneyJ
CourtneyJ

Reputation: 508

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 "/

Upvotes: 0

Views: 846

Answers (3)

CourtneyJ
CourtneyJ

Reputation: 508

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"),
  );

Upvotes: -2

Kinglish
Kinglish

Reputation: 23664

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)

Upvotes: 1

Asplund
Asplund

Reputation: 2486

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()
);

Upvotes: 4

Related Questions