gpt4 book ai didi

javascript - 如何使用多个日期时间列对 javascript 数组进行排序

转载 作者:行者123 更新时间:2023-11-30 11:31:43 29 4
gpt4 key购买 nike

给定以下数组:

var effectiveDates= [
{
actualDate: "2017-08-29",
effectiveDate: "2017-01-01",
time: "13:22"
},
{
actualDate: "2017-08-29",
effectiveDate: "2017-01-01",
time: "11:33"
},
{
actualDate: "2017-08-29",
effectiveDate: "2017-01-01",
time: "10:57"
},
{
actualDate: "2016-06-17",
effectiveDate: "2016-01-01",
time: "10:26"
},
{
actualDate: "2016-06-17",
effectiveDate: "2016-01-01",
time: "10:03"
},
{
actualDate: "2015-12-03",
effectiveDate: "2015-01-01",
time: "16:54"
},
{
actualDate: "2014-07-07",
effectiveDate: "2014-05-01",
time: "10:47"
},
{
actualDate: "2014-07-07",
effectiveDate: "2014-05-01",
time: "10:41"
},
{
actualDate: "2014-07-07",
effectiveDate: "2014-01-01",
time: "10:36"
},
{
actualDate: "2014-07-07",
effectiveDate: "2014-01-01",
time: "10:36"
}
]

我正在尝试根据 actualDateeffectiveDate 降序(或升序,具体取决于顺序)对数据进行排序,然后按时间排序(也基于时间升序或降序所需的顺序)。我遇到的问题是日期顺序正确,但 time 属性顺序不正确。我正在使用 moment.js 进行日期和时间解析。

这是我到目前为止尝试过的:

var desc = true; //false;
effectiveDates.sort(function (a, b) {
if (desc) {
if (moment(a.actualDate) === moment(b.actualDate)) {
return (moment(b.time) - moment(a.time));
} else if (moment(a.actualDate) < moment(b.actualDate)) {
return 1;
} else if (moment(a.actualDate) > moment(b.actualDate)) {
return -1;
}
}
else {
if (moment(a.actualDate) === moment(b.actualDate)) {
return (moment(b.time) - moment(a.time));
} else if (moment(a.actualDate) > moment(b.actualDate)) {
return 1;
} else if (moment(a.actualDate) < moment(b.actualDate)) {
return -1;
}
}
});

出于某种原因,当按 effectiveDate 升序或降序对数据进行排序时,time 的排序是正确的。但是当按 actualDate 对数据进行排序时,同样是升序或降序,time 数据不正确。

如有任何帮助,我们将不胜感激。

最佳答案

代替

return (moment(b.time) - moment(a.time));

使用:

moment(a.time, "HH:mm") - moment(b.time, "HH:mm")

您需要告诉 moment.js 输入字符串是“时间”字符串。

关于javascript - 如何使用多个日期时间列对 javascript 数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46003063/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com