Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a JSON array on time, displayed in a 12 hour format

I have a JSON like the following

[
  {
    "Event_code": "AB-001",
    "Start_time": "11:00 AM",
    "End_time": "3:00 PM",
    "Session_type": "Tour"
  },
  {
    "Event_code": "AB-002",
    "Start_time": "09:30 AM",
    "End_time": "1:00 PM",
    "Session_type": "Course information session"
  },
  {
    "Event_code": "AB-003",
    "Start_time": "9:00 AM",
    "End_time": "3:00 PM",
    "Session_type": "General information session"
  }
]

All I want to do is sort the array on Start time ... I have seen a solution here but I am not sure how to tweak it to my JSON structure ...

Can someone please advise...!

like image 606
Slyper Avatar asked May 29 '18 02:05

Slyper


2 Answers

You just need to access the Start_time property of each object in the sort function:

const arr=[{"Event_code":"AB-001","Start_time":"11:00 AM","End_time":"3:00 PM","Session_type":"Tour"},{"Event_code":"AB-002","Start_time":"09:30 AM","End_time":"1:00 PM","Session_type":"Course information session"},{"Event_code":"AB-003","Start_time":"9:00 AM","End_time":"3:00 PM","Session_type":"General information session"}]
const dateFromStr = str => new Date('1970/01/01 ' + str);
arr.sort((a, b) => dateFromStr(a.Start_time) - dateFromStr(b.Start_time));
console.log(arr);
like image 69
CertainPerformance Avatar answered Oct 21 '22 12:10

CertainPerformance


You can simply sort your objects array based on the Start_time. We create a new Date obj within the sort function to make sure we can compare the milliseconds value correctly with subtraction.

const times = [{"Event_code":"AB-001","Start_time":"11:00 AM","End_time":"3:00 PM","Session_type":"Tour"},{"Event_code":"AB-002","Start_time":"09:30 AM","End_time":"1:00 PM","Session_type":"Course information session"},{"Event_code":"AB-003","Start_time":"9:00 AM","End_time":"3:00 PM","Session_type":"General information session"}]
times.sort(function (a, b) {return new Date('1970/01/01 ' + a.Start_time) - new Date('1970/01/01 ' + b.Start_time);});
console.log(times);
like image 41
sparta93 Avatar answered Oct 21 '22 12:10

sparta93