Home > database >  Sorting an array based on times
Sorting an array based on times

Time:04-21

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

CodePudding user response:

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

CodePudding user response:

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)

CodePudding user response:

This is the solution that worked best for me:

const sortedAppointments = appointments.sort(
    (a, b) => moment(a.start).format("x") - moment(b.start).format("x"),
  );

CodePudding user response:

var a = [['9:04 AM', '9:34 AM'], ['3:04 AM', '3:34 AM'], ['3:34 PM', '3:44 PM'],['1:24 PM', '3:34 PM']];


a.sort(sortFunction);

function sortFunction(a, b) {
    //alert(2);
    val1 = moment(a[0],["hh:mm A"]).format("HH:mm");
    val2 = moment(b[0],["hh:mm A"]).format("HH:mm");
    if (val1 === val2 ) {
        return 0;
    }
    else {
        return (val1 < val2) ? -1 : 1;
    }
}
         //document.getElementById("todaysdate").innerHTML = a;
         for (i = 0; i < a.length; i  )
            document.writeln((i 1)   ": "   a[i]   '<br>');
<html>
   <head>
      <title>MomentJS - Working Example</title>
      <script type = "text/JavaScript" src = "https://MomentJS.com/downloads/moment.js"></script>
      
   </head>
   <body>
      
     
   </body>
</html>

  • Related