我正在尝试使用js类型的luxon对象。我不确定这是否正确,因为排序需要-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")))
发布于 2020-11-12 18:22:13
您可以直接获取字符串,以便与String#localeCompare进行比较。
(a, b) => b.created.localeCompare(a.created)发布于 2020-11-16 17:34:04
您可能希望将DateTime对象设置为数字Unix时间戳:
function compareLuxonDates(a: DateTime, b: DateTime) {
return a.toMillis() - b.toMillis()
}
arrayWithDateObjects.sort(compareLuxonDates)发布于 2021-01-16 00:43:09
Luxon的DateTime类According to their docs实现了#valueof,它返回对象的原始值-在本例中是纪元毫秒。这意味着您可以在排序时直接使用<或>来比较Luxon DateTime对象。
这是一个我有时用来对Luxon DateTime数组进行排序的一行compareFn。
快速回答
sortDateTimes = (a, b) => a < b ? -1 : a > b ? 1 : 0;这种方法之所以有效,是因为相等性是一个通用的条件(最后的0 )。尽管您可以自由地将<和>与DateTime对象一起使用,但不能仅使用 ===来检查等价性。Luxon为此提供了一个.equals(...)函数。或者,因为它们实现了#valueOf,所以您可以使用+将DateTime对象转换为它们的原始值。
const { DateTime } = require('luxon');
a = DateTime.fromISO('2020-01-15');
b = DateTime.fromISO('2020-01-15');
a === b; // false
+a === +b; // true上面的小compareFn一行程序在DateTime对象数组上工作得很好,但由于我们经常希望对DateTime嵌入到属性(如created)中的对象数组进行排序,所以我们必须采取稍微不同的方法。
sortByCreated = (a, b) =>
a.created < b.created ? -1 : a.created > b.created ? 1 : 0;强健的答案
对于加分,使用函数生成器使其更具可重用性。
createPropertySorter = (propertyName) => (a, b) =>
a[propertyName] < b[propertyName] ? -1 : a[propertyName] > b[propertyName] ? 1 : 0;然后,当您需要排序时,将使用生成器,而不是直接使用排序函数本身。来自OP的例子:
const results = objectGroupedByYearMonth[year][month].results.sort(
createPropertySorter('created')
);
// results is now sorted, e.g. results.map(JSON.stringify) is
// [
// '{"name":"some Object","created":"2020-01-25T00:00:00.000-07:00"}',
// '{"name":"some Object","created":"2020-01-31T00:00:00.000-07:00"}',
// '{"name":"some Object","created":"2020-02-01T00:00:00.000-07:00"}',
// '{"name":"some Object","created":"2020-02-01T00:00:00.000-07:00"}',
// '{"name":"some Object","created":"2020-02-07T00:00:00.000-07:00"}'
// ]注意可变性
关于可变性:在上面的示例中,objectGroupedByYearMonth[year][month]有一个名为results的属性。因为sort()就地对数组进行排序,所以objectGroupedByYearMonth[year][month].results也会进行排序(不仅仅是返回值)。这可能是OP的意图,也可能是无关紧要的,但我认为这是值得注意的。保留原始排序的修订版本将使用扩展运算符对原始数组的副本进行排序。
const results = [...objectGroupedByYearMonth[year][month].results].sort(
createPropertySorter('created')
);
// results is sorted, while objectGroupedByYearMonth[year][month].results
// is still in its original order反向排序
如果要颠倒排序顺序(最新日期优先),请在排序函数中切换a和b。
createPropertyReverseSorter = (propertyName) => (a, b) =>
b[propertyName] < a[propertyName] ? -1 : b[propertyName] > a[propertyName] ? 1 : 0;https://stackoverflow.com/questions/64801992
复制相似问题