Yes, it's because you can't parse your formatted date with new Date
. Both 24/1/2021 @ 13:21:2
, and 24/1/2021 13:21:2
return Invalid Date if you try to parse them.
You can either update the way you store those dates or parse the date before you try to sort them. If you can't store them in a different format (e.g. ISO 8601), I'd probably use date-fns/parse
to parse the date with a custom formatter. See the example below:
import parse from 'date-fns/parse'
const chats = [
{ message: 'facilis consectetur, error sequi excepturi', last_updated: '24/1/2021 @ 13:21:2' },
{ message: 'sit amet consectetur adipisicing elit', last_updated: '24/1/2021 @ 13:20:14' },
{ message: 'mollitia unde fugiat delectus sunt ducimus', last_updated: '24/1/2021 @ 13:22:4' }
]
const format = 'd/M/y @ H:m:s'
const parseDate = d => parse(d, format, new Date())
chats.sort((a, b) => parseDate(b.last_updated) - parseDate(a.last_updated))
// it returns the following array:
//
// [
// {last_updated: "24/1/2021 @ 13:22:4", message: "mollitia unde fugiat delectus sunt ducimus"},
// {last_updated: "24/1/2021 @ 13:21:2", message: "facilis consectetur, error sequi excepturi"},
// {last_updated: "24/1/2021 @ 13:20:14", message: "sit amet consectetur adipisicing elit"}
// ]