-3

So here's what my array of objects currently looks like.

var array = 
[
{"time":"1:00 AM"}
{"time":"2:15 AM"}
{"time":"3:00 AM"}
{"time":"4:30 AM"}
{"time":"5:00 AM"}
{"time":"6:00 AM"}
{"time":"7:00 AM"}
{"time":"8:00 AM"}
{"time":"9:00 AM"}
{"time":"10:00 AM"}
{"time":"11:00 AM"}
{"time":"12:00 PM"}
{"time":"1:00 PM"}
{"time":"2:00 PM"}
{"time":"12:00 AM"}
{"time":"12:15 AM"}
{"time":"12:30 AM"}
]

I am trying to order them into the following order

var array = 
[
{"time":"12:00 AM"}
{"time":"12:15 AM"}
{"time":"12:30 AM"}
{"time":"1:00 AM"}
{"time":"2:15 AM"}
{"time":"3:00 AM"}
{"time":"4:30 AM"}
{"time":"5:00 AM"}
{"time":"6:00 AM"}
{"time":"7:00 AM"}
{"time":"8:00 AM"}
{"time":"9:00 AM"}
{"time":"10:00 AM"}
{"time":"11:00 AM"}
{"time":"12:00 PM"}
{"time":"1:00 PM"}
{"time":"2:00 PM"}
]

How would I do this?

I've tried sorting but the AM and PM is throwing things offer. I really appreciate all of the efforts of this community in helping people like me understand how to code better :)

2 Answers2

0
var objs = [
    {ref_time:"00:30 pm"},
    {ref_time:"10:30 pm"},
    {ref_time:"00:30 pm"},
    {ref_time:"03:30 pm"},
    {ref_time:"04:30 am"},
    {ref_time:"02:30 pm"},
    {ref_time:"11:30 am"},
    {ref_time:"09:30 pm"}
]  
 
function compare(a,b) {
    var time1 = parseFloat(a.ref_time.replace(':','.').replace(/[^\d.-]/g, ''));
    var time2 = parseFloat(b.ref_time.replace(':','.').replace(/[^\d.-]/g, ''));
    if(a.ref_time.match(/.*pm/)) time1 += 12; if(b.ref_time.match(/.*pm/)) time2 += 12;
    if (time1 < time2) return -1;
    if (time1 > time2) return 1;
    return 0;
}  

objs.sort(compare);

console.log(objs);
-1

I am currently on the phone so testing code is hard but i can give you a idea. Since AM and PM are the ones screwing you over you could try to make a function that convert "2:00 PM" to "14:00". This should be relative simple.

  1. detect if its am or pm.
  2. strip the "am" or pm tag.
  3. if its pm get the time and add 12 hours.
  4. Use the new time to sort.
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-ask). – Community Sep 15 '21 at 17:01