I have an array of object such as
[{
time: "13:20",
key2: "",
key3: ""
}, {
time: "13:40",
key2: "",
key3: ""
}, {
time: "04:20",
key2: "",
key3: ""
}]
and I want them to sort according to time. I did some research on momentjs but I didn't found something useful.
The main problem I am facing is How to convert that time that I am getting into String format to some comparable format for sorting. Any kind of help will be appreciated.Thank you.
You make a same date for all the times. And then getTime()
and compare that
let arr = [{
time: "13:20",
key2: "",
key3: ""
}, {
time: "13:40",
key2: "",
key3: ""
}, {
time: "04:20",
key2: "",
key3: ""
}]
const toTime = (t) => new Date(`December 17, 1995 ${t}`).getTime();
arr.sort((a,b) => toTime(a.time) - toTime(b.time))
console.log(arr)
You can take following approach to sort it:
Benefit of having date based approach is that it will handle all time value cases. I have updated data to have second values as well for demonstration
var data = [{
time: "13:20",
key2: "",
key3: ""
}, {
time: "13:40",
key2: "",
key3: ""
}, {
time: "04:20:10",
key2: "",
key3: ""
}, {
time: "04:20:20",
key2: "",
key3: ""
}];
function getAddedTimeValue(time) {
const parts = [...time.split(':'), 0, 0, 0, 0].slice(0, 4);
const date = new Date();
date.setHours.apply(date, parts);
return date.getTime();
}
data.sort((a, b) => getAddedTimeValue(a.time) - getAddedTimeValue(b.time));
// For descending:
// data.sort((a, b) => getAddedTimeValue(b.time) - getAddedTimeValue(a.time));
console.log(data)
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