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

305
Views
¿Cómo puedo ordenar los tiempos de dayjs ()?

Tengo una serie de objetos como este:

 [ {name: 'John Smith', date: '10:30 AM'}, {name: 'Jo Smith', date: '8:30 AM'}, {name: 'Ela Smith', date: '1:00 PM'}, {name: 'Dave Smith', date: '12:30 PM'}, {name: 'Elton Smith', date: '10:30 PM'} ]

Me gustaría ordenarlos de más antiguo a más reciente usando dayjs() que es lo que estamos usando para el resto de nuestro proyecto, así que tengo que seguir con eso.

Por el momento estoy tratando de usar esta función así:

 dayjs.extend(isSameOrBefore); dayjs.extend(customParseFormat); const sortTime = (users) => { return shifts.sort((a, b) => dayjs(a.date, 'h:mm A').isSameOrBefore(dayjs(b.date, 'h:mm A')) ? 1 : -1 ); };

Me gustaría que la matriz se ordenara así:

 [ {name: 'Jo Smith', date: '8:30 AM'}, {name: 'John Smith', date: '10:30 AM'}, {name: 'Elton Smith', date: '10:30 AM'}, {name: 'Dave Smith', date: '12:30 PM'}, {name: 'Ela Smith', date: '1:00 PM'} ]

Sin embargo, por alguna extraña razón, se ordena así:

 [ {name: 'Jo Smith', date: '8:30 AM'}, {name: 'Ela Smith', date: '1:00 PM'}, {name: 'John Smith', date: '10:30 AM'}, {name: 'Dave Smith', date: '12:30 PM'}, {name: 'Elton Smith', date: '10:30 AM'}, ]

¿Alguna idea de por qué y cómo puedo solucionar esto?

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

0

Puede lograr el resultado utilizando la función de comparación de paso para ordenar el método como

 const arr = [ { name: "John Smith", date: "10:30 AM" }, { name: "Jo Smith", date: "8:30 AM" }, { name: "Ela Smith", date: "1:00 PM" }, { name: "Dave Smith", date: "12:30 PM" }, { name: "Elton Smith", date: "10:30 PM" }, ]; const convertTime12to24 = (time12h) => { let [hours, minutes, modifier] = time12h.split(/\W+/); if (hours === "12") hours = "00"; if (modifier === "PM") hours = parseInt(hours, 10) + 12; return [hours, minutes]; }; const result = arr.sort((a, b) => { const [h1, m1] = convertTime12to24(a.date); const [h2, m2] = convertTime12to24(b.date); return h1 - h2 || m1 - m2; }); console.log(result);
 /* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */ .as-console-wrapper { max-height: 100% !important; top: 0; }

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!