JavaScript排序日期后跟时间降序排列

时间:2017-12-27 00:55:57

标签: javascript sorting date time

我遇到了一些问题,使用JavaScript按日期降序排序日期。以下是一些意见:

[{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"}]

我想按降序对它们进行排序,最新的一个会在最重要的位置,但我不知道该怎么做。

所需的输出:

[{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"}]

如果结果来自同一天,那么我会根据时间排序。否则,最新日期将在最前面。有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

只需连结datetime,然后将其解析为Date并获取时间戳。从那以后,它只是简单的旧分类。

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)

更新:Marcel Gwerder评论中的链接答案表示您可以完全跳过getTime()并仅比较日期。