javascript - 如何使用反应根据日期对对象内的数据进行排序?
问题描述
我有如下的数据结构,
const items = {
id: '1',
Orders: [
{
id: '1',
title: 'Order1',
startDate: "2019-08-13T00:00:00.000Z",
status: 'new',
}
{
id: '2',
title: 'Order2',
startDate: "2020-08-13T00:00:00.000Z",
status: 'done',
}
],
subItems: [
{
id: '1',
Orders: [
{
id: '1',
title: 'subitem-order1',
status: 'new',
startDate: '2019-08-13T00:00:00.000Z',
}
{
id: '2',
title: 'subitem-order2',
status: 'new',
startDate: '2020-08-13T00:00:00.000Z',
}
]
}
]
}
我想按 startdate 升序排列订单,按 startdate 升序排列子项订单。
所以输出应该如下所示,
const items = {
orders: [
{
id: '2',
title: 'Order2',
startDate: "2020-08-13T00:00:00.000Z",
status: 'done',
},
{
id: '1',
title: 'Order1',
startDate: "2019-08-13T00:00:00.000Z",
status: 'new',
},
]
subItems: [
{
id: '2',
title: 'subitem-order2',
status: 'new',
startDate: '2020-08-13T00:00:00.000Z',
},
{
id: '1',
title: 'Order1',
startDate: "2019-08-13T00:00:00.000Z",
status: 'new',
},
]
}
如何根据开始日期按升序对订单进行分组,如何根据开始日期按升序对子项订单进行分组。有人可以帮我解决这个问题。谢谢。
解决方案
幸运的是,您的 startDate 是 ISO 日期时间,因此按字母顺序排序将提供正确的时间顺序。让我们利用它!
请记住,您排序的键是字符串,而不是数字。按字符串键排序的一种方便方法是使用 localeCompare,它具有获取两个字符串并返回一个适合排序的数字的有用功能。
因为使用 localeCompare 很容易进行排序,所以您可以将每个列表的排序作为一个单行进行,这允许您以易于理解的方式“构建”结果对象,如下所示:
const rawItems = {
orders: [
{
id: '2',
title: 'Order2',
startDate: "2020-08-13T00:00:00.000Z",
status: 'done',
},
{
id: '1',
title: 'Order1',
startDate: "2019-08-13T00:00:00.000Z",
status: 'new',
},
],
subItems: [
{
id: '2',
title: 'subitem-order2',
status: 'new',
startDate: '2020-08-13T00:00:00.000Z',
},
{
id: '1',
title: 'Order1',
startDate: "2019-08-13T00:00:00.000Z",
status: 'new',
},
]
}
const items = {
orders: rawItems.orders.sort(
(order1,order2) => order1.startDate.localeCompare(order2.startDate)
),
subitems: rawItems.subItems.sort(
(sub1,sub2) => sub1.startDate.localeCompare(sub2.startDate)
),
}
console.log(items)
在问题中,您反复指定“升序”顺序,即先小值,后大值。但是,您给出的示例答案是降序排列的。
正如您指定的那样,我提供的示例答案是升序的。如果您的意思是“降序”,则只需localeCompare
按如下方式否定值:
(order1,order2) => -order1.startDate.localeCompare(order2.startDate)
和
(sub1,sub2) => -sub1.startDate.localeCompare(sub2.startDate)
推荐阅读
- c# - Office 365 公共日历示例
- google-analytics - 如何使用 Google Analytics API 提取 GA 帐户更改历史记录?
- python - 为什么带有自定义绘画的小部件不可见?
- html - 是否可以强制屏幕阅读器读取字段集的内部内容?
- python - 如何从列表中识别第一个和最后一个节点及其组 - Python
- javascript - 取消选择数据表行后如何正确删除数组中的索引或值?
- c - C 填充二维数组
- python - 将列数多于预期的数据读入数据框中
- machine-learning - lightgbm 的超参数调整
- java - 如何在 IntelliJ IDEA 2018.2 中调试在 Docker 容器中运行的 Java 应用程序?