JavaScript如何查找数组中满足指定时长的连续可用预约时隙
解决方案
直接封装一个可复用的通用函数,支持传入任意需要的时隙数(1~4都适配),逻辑清晰且扩展性强:
/** * 筛选符合要求的起始预约时隙 * @param {Array} availableSlots 已过滤掉不可用的、按Timeslot升序排序的时隙数组 * @param {Number} requiredSlots 本次预约需要的连续时隙数量(1~4) * @returns {Array} 符合要求的起始时隙列表,带linkedIds字段 */ function getValidStartSlots(availableSlots, requiredSlots) { // 边界异常处理 if (requiredSlots < 1 || requiredSlots > 4 || availableSlots.length < requiredSlots) { return [] } const SLOT_INTERVAL = 30 // 单时隙固定间隔30分钟 // 遍历所有可能的起始下标,过滤符合连续要求的项,再格式化输出 return Array.from({ length: availableSlots.length - requiredSlots + 1 }, (_, i) => i) .filter(startIndex => { // 检查从startIndex开始的requiredSlots个时隙是否连续 for (let offset = 1; offset < requiredSlots; offset++) { const current = availableSlots[startIndex + offset] const prev = availableSlots[startIndex + offset - 1] if (current.Timeslot !== prev.Timeslot + SLOT_INTERVAL) { return false } } return true }) .map(startIndex => { const startSlot = availableSlots[startIndex] // 提取连续时隙的id数组 const linkedIds = Array.from({ length: requiredSlots }, (_, offset) => availableSlots[startIndex + offset].id) return { ...startSlot, linkedIds } }) }
使用示例
针对你给出的示例场景,传入需要4个时隙的参数即可得到目标结果:
// 你的示例可用时隙数组 const exampleArray = [ {id: 1, Timeslot: 480, displayText: '8am'}, {id: 2, Timeslot: 510, displayText: '8:30am'}, {id: 3, Timeslot: 540, displayText: '9am'}, {id: 4, Timeslot: 570, displayText: '9:30am'}, {id: 5, Timeslot: 600, displayText: '10am'}, {id: 6, Timeslot: 630, displayText: '10:30am'}, {id: 7, Timeslot: 690, displayText: '11:30am'}, {id: 8, Timeslot: 720, displayText: '12pm'}, {id: 9, Timeslot: 750, displayText: '12:30pm'}, {id: 10, Timeslot: 780, displayText: '1pm'}, {id: 11, Timeslot: 840, displayText: '2pm'}, {id: 12, Timeslot: 870, displayText: '2:30pm'}, {id: 13, Timeslot: 900, displayText: '3pm'}, {id: 14, Timeslot: 930, displayText: '3:30pm'}, ] // 查询需要4个连续时隙的可用起始位 const result = getValidStartSlots(exampleArray, 4) console.log(result) // 输出和你要求的示例结果完全一致
注意事项
- 传入的
availableSlots需要提前按Timeslot字段升序排序,一般从数据库查询可用时隙时直接加排序条件即可,符合常规业务逻辑 - 注意字段名大小写,你之前的测试代码里用了小写的
timeslot,示例数组里是首字母大写的Timeslot,实际使用时保持一致即可避免报错 - 如果后续单时隙时长规则变更,只需要修改常量
SLOT_INTERVAL的值即可适配
内容的提问来源于stack exchange,提问作者trig79
相关产品推荐
相关产品推荐

