2

I was having some problem to sort the date followed by time in descending order using JavaScript. Here is some inputs:

[{chatroomID: "1", date: "12/26/2017", time: "10:31:32 PM"},
{chatroomID: "2", date: "12/26/2017", time: "10:38:01 PM"},
{chatroomID: "3", date: "12/26/2017", time: "10:35:14 PM"}]

I wanted to sort them in descending order whereby the latest one will be on top but I not sure how to do it.

The desired output:

[{chatroomID: "2", date: "12/26/2017", time: "10:38:01 PM"},
{chatroomID: "3", date: "12/26/2017", time: "10:35:14 PM"},
{chatroomID: "1", date: "12/26/2017", time: "10:31:32 PM"}]

If the result comes from the same date, then I will sort according to time. Otherwise, the latest date will be on top. Any ideas?

Thanks!

1

1 Answer 1

7

Just concat the date and time, then parse it to a Date and get the timestamp. From then on, it's just plain old sorting.

const datetimes = [
  {chatroomID: "1", date: "12/26/2017", time: "10:31:32 PM"},
  {chatroomID: "2", date: "12/26/2017", time: "10:38:01 PM"},
  {chatroomID: "3", date: "12/26/2017", time: "10:35:14 PM"}
]

const sorted = datetimes.sort((a, b) => {
  const aDate = new Date(a.date + ' ' + a.time)
  const bDate = new Date(b.date + ' ' + b.time)
  
  return bDate.getTime() - aDate.getTime()
})

console.log(sorted)

Update: The linked answer in the comment by Marcel Gwerder indicates you could just skip getTime() altogether and just compare the Dates.

Sign up to request clarification or add additional context in comments.

2 Comments

I think using new Date or Date.parse with a string sill isn't a really safe thing to do, see the note on MDN.
@MarcelGwerder Fair point - I doubt browsers will be inconsistent with the OP's formats - but I wouldn't swear on this.