Dayjs: Sorting with dayjs not working as expected

Created on 5 Sep 2018  路  2Comments  路  Source: iamkun/dayjs

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.

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.

All 2 comments

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!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

dakshshah96 picture dakshshah96  路  5Comments

g1eny0ung picture g1eny0ung  路  4Comments

Sunrise1970 picture Sunrise1970  路  4Comments

scottsandersdev picture scottsandersdev  路  3Comments

eugeneoshepkov picture eugeneoshepkov  路  3Comments