微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何对luxon对象数组执行排序 注意可变性反向排序

如何解决如何对luxon对象数组执行排序 注意可变性反向排序

我正在尝试使用js类的luxon时间对象。我不确定排序是否正确-1,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")))

解决方法

您可以直接将字符串与String#localeCompare进行比较。

(a,b) => b.created.localeCompare(a.created)
,

According to their docs,Luxon 的 DateTime 类实现了 #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"}',"created":"2020-02-01T00:00:00.000-07:00"}',"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

反向排序

如果要颠倒排序顺序(最新日期在前),请在排序函数中切换 ab

createPropertyReverseSorter = (propertyName) => (a,b) =>
  b[propertyName] < a[propertyName] ? -1 : b[propertyName] > a[propertyName] ? 1 : 0;
,

您可能希望将DateTime对象convert设置为数字Unix时间戳:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。