3

Sort JavaScript Object Array By Date (mm/DD/yyyy hh/mm/ss Am/Pm)

var array = [
  { id: 1, date: Mar 12 2017   10:00:00 AM }, 
  { id: 2 ,date: Mar 12 2017   08:00:00 PM },
  { id: 3, date: Mar 12 2017   05:00:00 AM },
  { id: 4, date: Mar 18 2017   09:00:00 AM }
];

Here is my logic:-
sortedPatients = PatientsListArray.sort((a, b) =>
            b.Date.split('/')
              .reverse()
              .join()
              .localeCompare(
                a.Date.split('/')
                  .reverse()
                  .join()
              )
          )

Got output like this id4 , id1 , id2 , id3

Expected output like this id4, id2, id3, id1

matisetorm
  • 847
  • 8
  • 21
sai
  • 119
  • 1
  • 7

1 Answers1

2

const array = [
  {id: 1, date: 'Mar 12 2017   10:00:00 AM'},
  {id: 2, date: 'Mar 12 2017   08:00:00 PM'},
  {id: 3, date: 'Mar 12 2017   05:00:00 AM'},
  {id: 4, date: 'Mar 18 2017   09:00:00 AM'},
];

console.log(
  array.sort((a, b) => new Date(b.date) - new Date(a.date))
);

With this callback function in the sort method you get the order of id4, id2, id1 and id3. I don't understand why you'd like to get the order id4, id2, id3 and id1.

If you want a reversed order, just swap the positions of b and a so that you have (a, b) => new Date(a.date) - new Date(b.date).

If you already have Date objects (looks like it as you have used b.Date and a.Date in your code), you could write something like this:

sortedPatients = PatientsListArray.sort((a, b) => b.Date - a.Date))
Matias Kinnunen
  • 5,463
  • 3
  • 27
  • 30