I have an array of objects like so :
var example = [{
"description": "aaa",
"time": "12:15pm"
}, {
"description": "bbb",
"time": "10:10am"
}, {
"description": "ccc",
"time": "4:00pm"
}, {
"description": "ddd",
"time": "6:15pm"
}, {
"description": "eee",
"time": "1:10am"
}, {
"description": "fff",
"time": "5:00pm"
} ];
I want to sort by the time
value.
I have tried to apply this solution which was intended for an array of string values:
example.sort(function (a, b) {
return new Date('1970/01/01 ' + a.time) - new Date('1970/01/01 ' + b.time);
});
console.log(example);
I've also been referring to the Mozilla Array.prototype.sort() documentation and tried the following which didn't seem to work:
example.sort(function(a, b) {
if (new Date(a.time) > new Date(b.time)) {
return 1;
}
if (new Date(a.time) < new Date(b.time)) {
return -1;
}
// a must be equal to b
return 0;
});
console.log(example);
The date string that you are generating is not valid so it will always returns current date and time. So generate valid date string(eg : '1970/01/01 9:34:48 AM'
) then parse and return the difference. Here String#slice()
method can be used to generate the valid date string.
var example = [{
"description": "aaa",
"time": "12:15pm"
}, {
"description": "bbb",
"time": "10:10am"
}, {
"description": "ccc",
"time": "4:00pm"
}, {
"description": "ddd",
"time": "6:15pm"
}, {
"description": "eee",
"time": "1:10am"
}, {
"description": "fff",
"time": "5:00pm"
}];
example.sort(function(a, b) {
// get time time from string
// then get am or pm from string and append
// both can be done using slice method
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(example);
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