You need to enable JavaScript to run this app. 如何从体育场地预订对象数组中查找3个场地共有的起止时间
优惠活动
大模型
产品
解决方案
定价
更多

如何从体育场地预订对象数组中查找3个场地共有的起止时间

全场地共同预订时段筛选实现方案

核心思路

要筛选出3个场地同时存在的已预订共同时段,核心是先把所有预订记录按起止时间区间做聚合,再校验每个区间下覆盖的场地数量是否等于总场地数(3个),符合条件的区间就是目标结果。

具体实现代码

// 配置总场地数量,可随业务调整
const TOTAL_COURT_COUNT = 3;
const bookingList = [
    {start: "12:00", end: "13:00", court:1},
    {start: "10:00", end: "11:00", court:1},
    {start: "12:00", end: "13:00", court:2},
    {start: "15:00", end: "16:00", court:3},
    {start: "12:00", end: "13:00", court:3}
];

// 1. 按时间区间聚合对应场地
const slotCourtMap = bookingList.reduce((acc, item) => {
    // 用起止时间拼接成唯一的区间标识
    const slotKey = `${item.start}#${item.end}`;
    if (!acc[slotKey]) {
        acc[slotKey] = {
            start: item.start,
            end: item.end,
            courtSet: new Set()
        };
    }
    acc[slotKey].courtSet.add(item.court);
    return acc;
}, {});

// 2. 筛选出覆盖全部场地的共同时段
const commonSlots = Object.values(slotCourtMap)
    .filter(slot => slot.courtSet.size === TOTAL_COURT_COUNT)
    .map(({start, end}) => ({start, end}));

console.log(commonSlots);
// 运行输出: [{start: '12:00', end: '13:00'}]

方案特性

  • 单轮遍历完成聚合,时间复杂度为O(n),数据量较大时也能保持稳定性能
  • 用Set存储对应场地,自动过滤同一场地、同一时段的重复预订脏数据
  • 总场地数可灵活配置,后续场地数量增减不需要改动核心筛选逻辑
  • 输出结构完全匹配业务要求的{start, end}格式,无需额外转换

内容的提问来源于stack exchange,提问作者avoshmo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.10 06:36:00