1

I'm trying to figure out how to order an array which includes Date objects inside.

Here my array Appointment[] is below(contains 3 objects)

0: {id: 36, appointmentDate: "2019-12-27T10:28:15"}
1: {id: 57, appointmentDate: "2020-01-03T08:29:25"}
2: {id: 58, appointmentDate: "2020-01-15T15:45:19"}

Here's the method I tried to implement but didn't work it says a.appointmentDate.getTime is not a function

if(param === 'a'){
      return value.sort((a, b) => { return a.appointmentDate.getTime() - b.appointmentDate.getTime() });
}

Here also another approach didn't work either below says

The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type

  if(param === 'a'){
  return value.sort((a, b) => { return new Date(a.appointmentDate) - new Date(b.appointmentDate});
    }
Touheed Khan
  • 2,149
  • 16
  • 26
Timuçin Çiçek
  • 1,516
  • 3
  • 14
  • 39
  • Directly use string sorting: `a.appointmentDate.localeCompare(b.appointmentDate)`. If you want to use Date constructor add `+` in front of the date objects: `+new Date(a.appointmentDate)`. Typescript doesn't like subtracting dates and type coercion – adiga Dec 27 '19 at 13:05
  • The first one throws an error because `appointmentDate` is a string and not a `Date`. The second error is from TypeScript because it doesn't allow the `-` operation on `Date` objects. Just check the documentation for `Date` if there is a method/property that returns a numerical representation of the date. – Andreas Dec 27 '19 at 13:06

1 Answers1

1

Combine your two efforts:

if(param === 'a'){
  return value.sort((a, b) => { return new Date(a.appointmentDate).getTime() - new Date(b.appointmentDate).getTime() })
}
C.OG
  • 6,236
  • 3
  • 20
  • 38