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

时间:2019-04-03 15:24:52

标签: javascript arrays node.js sorting

我得到了一个包含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之后出现

2 个答案:

答案 0 :(得分:2)

您可以获取事件的时长,然后按开始时间和结束时间进行排序。

serial

答案 1 :(得分:1)

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

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);