首页 > 解决方案 > 如何对 luxon 对象数组执行排序

问题描述

我正在尝试使用 js 类型的 luxon 时间对象。我不确定这是否如 sort 所期望的那样正确-1,0,1

const results  = objectGroupedByYearMonth[year][month].results.sort(
          (a,b) => 
            DateTime.fromISO(b.created)
              .diff(DateTime.fromISO(a.created))
        )

这将返回一个 dt 对象console.log("DIF: ", DateTime.fromISO("2020-11-03T17:01:22.205041Z") .diff(DateTime.fromISO("2020-11-03T17:15:23.998284Z")))

标签: javascriptsortingluxon

解决方案


您可能希望对象转换为DateTime数字 Unix 时间戳:

function compareLuxonDates(a: DateTime, b: DateTime) {
  return a.toMillis() - b.toMillis()
}
arrayWithDateObjects.sort(compareLuxonDates)

推荐阅读