Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

216
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda