1

I am unable to sort an array by date. I tried many different things but couldn't get it to work. An array consists of objects with a last_updated field that has a value formatted like this: 24/1/2021 @ 13:21:2.

I tried sorting the array before executing .map():

chats.sort(function (a, b) {
  return (
    new Date(b.last_update) - new Date(a.last_update)
  );
});

This does not work and I honestly don't know why. Is this because of the @ in the date?

Zsolt Meszaros
  • 21,961
  • 19
  • 54
  • 57
Lucdabomb
  • 233
  • 4
  • 15

3 Answers3

0

const chats = [
  { title: 'Hiking', last_updated: new Date('2019-06-28') },
  { title: 'Shopping', last_updated: new Date('2019-06-10') },
  { title: 'Trekking', last_updated: new Date('2019-06-22') }
]

const sorted = chats.sort((a, b) => b.last_updated - a.last_updated)

console.log(sorted);
Pulsara Sandeepa
  • 915
  • 10
  • 25
0

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"}
// ]
Zsolt Meszaros
  • 21,961
  • 19
  • 54
  • 57
-1

Try this:

chats.sort(function (a, b) {
  return new Date(b.last_update).getTime() - new Date(a.last_update).getTime();
});
Taghi Khavari
  • 6,272
  • 3
  • 15
  • 32