I have an array of objects
var data =[
{
"avail": "3 Bookings Available"
"time": "05:00 PM to 06:00 PM",
"date": "2018-01-30"
},
{
"avail": "3 Bookings Available",
"time": "09:00 AM to 10:00 AM",
"date": "2018-01-30"
},
{
"avail": "3 Bookings Available",
"time": "04:00 PM to 05:00 PM",
"date": "2018-01-30"
},
{
"avail": "3 Bookings Available",
"time": "03:00 PM to 04:00 PM",
"date": "2018-01-30"
}];
I want to sort data by its time string value so that the required output becomes like this below:
[{
"avail": "3 Bookings Available"
"time": "09:00 AM to 10:00 AM",
"date": "2018-01-30"
},
{
"avail": "3 Bookings Available",
"time": "03:00 PM to 04:00 PM",
"date": "2018-01-30"
},
{
"avail": "3 Bookings Available",
"time": "04:00 PM to 05:00 PM",
"date": "2018-01-30"
},
{
"avail": "3 Bookings Available",
"time": "05:00 PM to 06:00 PM",
"date": "2018-01-30"
}]
I have used the sort function with String #localeCompare but still i am not getting the required output
data.sort(function(a,b){
return a.time.localeCompare(b.time);
});
console.log(data);
even i used the String#slice() method by which i can be used to generate the valid date string using '1970/01/01' as an arbitrary date still i am getting the required out can anyone give me the way by which i can get the output in this manner Thanks in advance.
data.sort(function(a, b) {
return Date.parse('1970/01/01 ' + a.time.slice(0, -2) + ' ' + a.time.slice(-2)) - Date.parse('1970/01/01 ' + b.time.slice(0, -2) + ' ' + b.time.slice(-2))
});
Example:
var data = [{
"avail": "3 Bookings Available",
"time": "05:00 PM to 06:00 PM",
"date": "2018-01-30"
},
{
"avail": "3 Bookings Available",
"time": "09:00 AM to 10:00 AM",
"date": "2018-01-30"
},
{
"avail": "3 Bookings Available",
"time": "04:00 PM to 05:00 PM",
"date": "2018-01-30"
},
{
"avail": "3 Bookings Available",
"time": "03:00 PM to 04:00 PM",
"date": "2018-01-30"
}
];
data.sort(function(a, b) {
return Date.parse('1970/01/01 ' + a.time.slice(0, -2) + ' ' + a.time.slice(-2)) - Date.parse('1970/01/01 ' + b.time.slice(0, -2) + ' ' + b.time.slice(-2))
});
console.log(data)
new Date("2018-01-30T12:34:56")