I have a array of objects like this:
arr = [
{ id: '5', Time: '01:00', status: 'grey' },
{ id: '7', Time: '12:00', status: 'grey' },
{ id: '8', Time: '12:45', status: 'green' },
]
Result I'm trying to get like this:
[
{ id: '7', Time: '12:00', status: 'grey' },
{ id: '8', Time: '12:45', status: 'green' },
{ id: '5', Time: '01:00', status: 'grey' },
]
I am doing sort like this but not working:
arr = arr.sort(function (a, b) {
var a1 = a.Time;
var b1 = b.Time;
if (a1 == b1) return 0;
return a1 > b1 ? 1 : -1;
});
While debug I noticed for example arr[0].Time > arr[1].Time
gives me false
, but "1:00" > "12:00"
gives me true
.
My debug console is below.
I am using Chrome and Firefox and both giving same results. Any idea?
CodePudding user response:
You can convert them to a Date object.
const birthday = new Date('1995-12-17T03:24:00') // change 03:24
Then you can compare two dates. in one go
arr = [{
id: '5',
Time: '01:00',
status: 'grey'
},
{
id: '7',
Time: '12:00',
status: 'grey'
},
{
id: '8',
Time: '12:45',
status: 'green'
},
]
arr.sort(function(a,b) {
var date1 = (new Date("2000-01-01T" a.Time ":00")).getTime()
var date2 = (new Date("2000-01-01T" b.Time ":00")).getTime()
return (date1 < date2 ? -1 : (date1 > date2 ? 1 : 0))
})
console.log(arr)