Hello! I am using dayjs for a small project - and for a specific thing I required to sort some dates in ascending/descending order.
I tried the following code (here you can run it in runkit):
let n = [
'2018-10-05T10:30:00',
'2018-10-05T08:05:00',
'2018-10-05T08:20:00',
'2018-10-05T08:30:00',
'2018-10-05T10:10:00',
'2018-10-05T10:30:00',
'2018-10-05T11:15:00',
'2018-10-05T11:25:00',
'2018-10-05T12:00:00',
'2018-10-05T17:10:00',
'2018-10-05T22:05:00'
]
console.log(n.sort((a, b) => dayjs(a).isAfter(b)))
But the sorted array looks like this (marking with * the ones not in order)
[
'2018-10-05T10:30:00', *
'2018-10-05T10:30:00', *
'2018-10-05T08:20:00',
'2018-10-05T08:30:00',
'2018-10-05T10:10:00',
'2018-10-05T08:05:00', *
'2018-10-05T11:15:00',
'2018-10-05T11:25:00',
'2018-10-05T12:00:00',
'2018-10-05T17:10:00',
'2018-10-05T22:05:00'
]
I am unsure as to why this is happening. I just figured out that I don't really need dayjs for this, as .sort() does the work flawlessly based on .charAt(); but either I am doing something terribly wrong (which I don't discard) or the returned sorted values have something bogus inside.
Hi, @maeriens.
I belive you are using .sort method in the wrong way. Try this code, please:
https://runkit.com/embed/mpmqk4tnk79y
function must return 1, -1, or zero (if values are equals). Not true or false.
You're completely right, absolutely forgot about the numerical return value. Thanks for the quick response!
Most helpful comment
Hi, @maeriens.
I belive you are using .sort method in the wrong way. Try this code, please:
https://runkit.com/embed/mpmqk4tnk79y
function must return 1, -1, or zero (if values are equals). Not true or false.