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...!
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With