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!

  • 2
    First you should convert the dates and times to date objects then you should have a look at [Sort Javascript Object Array By Date](https://stackoverflow.com/questions/10123953/sort-javascript-object-array-by-date) – Marcel Gwerder Dec 27 '17 at 01:01

1 Answers1

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.

nicholaswmin
  • 21,686
  • 15
  • 91
  • 167
  • 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date). – Marcel Gwerder Dec 27 '17 at 01:07
  • @MarcelGwerder Fair point - I doubt browsers will be inconsistent with the OP's formats - but I wouldn't swear on this. – nicholaswmin Dec 27 '17 at 01:12