-1

I have a large array of objects with a string type date field with format dd/mm/yyyyy HH:mm:ss and I can't reorder it properly.

The array looks like this

cases[
   {
      name: a, 
      date:03/04/2020 17:24:17
   },
   {
      name: b, 
      date:04/05/2020 07:21:19
   },
   {
      name: c, 
      date:02/01/2020 11:35:50
   },
]

And I tried to reorder it in the following way but without results

cases.sort(function(a,b){
                   var dateA=new Date(a.date), dateB=new Date(b.date)
                   return dateA - dateB
        });

1 Answers1

0

Try this

cases = [{
  name: "a",
  date: "03/04/2020 17:24:17"
}, {
  name: "b",
  date: "04/05/2020 07:21:19"
}, {
  name: "c",
  date: "02/01/2020 11:35:50"
}, ]

const makeDate = str => {
  const [_, dd, mm, yyyy, hh, min, ss] = str.match(/(\d{2})\/(\d{2})\/(\d{4}) (\d{2}):(\d{2}):(\d{2})/);
  return new Date(yyyy, mm - 1, dd, hh, min, ss)
};

cases.sort((a, b) => makeDate(a.date) - makeDate(b.date))

console.log(cases)
mplungjan
  • 169,008
  • 28
  • 173
  • 236