gpt4 book ai didi

javascript - 根据 startTime 和 endTime 对数组进行排序

转载 作者:搜寻专家 更新时间:2023-11-01 00:34:58 24 4
gpt4 key购买 nike

我得到了一个包含 fromTime 和 endTime 的对象数组。我想对它们进行排序,以便在数组中首先获得 16:00-18:00,最后获得 16:00-21:00。我知道如何根据 endDate 进行过滤,但是我需要将 fromDate 考虑在内,有人可以帮助我朝着正确的方向前进吗?

"deliverySlots": [
{
"deliveryFromTime": "17:00",
"deliveryToTime": "19:00",
},
{
"deliveryFromTime": "18:00",
"deliveryToTime": "20:00",
},
{
"deliveryFromTime": "19:00",
"deliveryToTime": "21:00",
},
{
"deliveryFromTime": "16:00",
"deliveryToTime": "21:00",
},
{
"deliveryFromTime": "16:00",
"deliveryToTime": "18:00",
}
]

function compare(a,b) {
var time1 = parseFloat(a.deliveryToTime.replace(':','.').replace(/[^\d.-]/g, ''));
var time2 = parseFloat(b.deliveryToTime.replace(':','.').replace(/[^\d.-]/g, ''));
if (time1 < time2) return -1;
if (time1 > time2) return 1;
return 0;
}
deliverySlots.sort(compare);

目标:

"deliverySlots": [
{
"deliveryFromTime": "16:00",
"deliveryToTime": "18:00",
},
{
"deliveryFromTime": "17:00",
"deliveryToTime": "19:00",
},
{
"deliveryFromTime": "18:00",
"deliveryToTime": "20:00",
},
{
"deliveryFromTime": "19:00",
"deliveryToTime": "21:00",
},
{
"deliveryFromTime": "16:00",
"deliveryToTime": "21:00",
},
]

所以基本上我想优先排序 endDate,然后是 startDate。 16:00-21:00应该在19:00-21:00之后

最佳答案

创建一个函数来按对象的属性值对对象进行排序,如下所示:

var deliverySlots = [
{
"deliveryFromTime": "17:00",
"deliveryToTime": "19:00",
},
{
"deliveryFromTime": "18:00",
"deliveryToTime": "20:00",
},
{
"deliveryFromTime": "19:00",
"deliveryToTime": "21:00",
},
{
"deliveryFromTime": "16:00",
"deliveryToTime": "21:00",
},
{
"deliveryFromTime": "16:00",
"deliveryToTime": "18:00",
}
];


function compare(a,b) {
if (a.deliveryToTime < b.deliveryToTime || (a.deliveryToTime == b.deliveryToTime && a.deliveryFromTime > b.deliveryFromTime))
return -1;
if (a.deliveryToTime > b.deliveryToTime || (a.deliveryToTime == b.deliveryToTime && a.deliveryFromTime < b.deliveryFromTime))
return 1;
return 0;
}

deliverySlots.sort(compare);

console.log(deliverySlots);

关于javascript - 根据 startTime 和 endTime 对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55498809/

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