You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript数组对比补全:为缺失时段补充count=0的实现需求

完善JavaScript数据补全缺失时段功能

原始数据

const hours = [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24];

const data = [
    {
        _id: '6239f41e0a9e6ba82ebc9774',
        title: 'X',
        capacity: 60,
        inParkings: [
            { hour: 7, count: 5 },
            { hour: 19, count: 4 },
            { hour: 16, count: 1 },
            { hour: 8, count: 11 },
            { hour: 5, count: 4 },
            { hour: 9, count: 3 },
            { hour: 13, count: 12 },
            { hour: 14, count: 6 },
            { hour: 10, count: 9 },
            { hour: 23, count: 1 },
            { hour: 6, count: 1 },
            { hour: 12, count: 8 },
            { hour: 11, count: 3 },
        ],
    },
    {
        _id: '62725362d9575e262f51ed84',
        title: 'Y',
        capacity: 75,
        inParkings: [
            { hour: 13, count: 6 },
            { hour: 5, count: 1 },
            { hour: 14, count: 2 },
            { hour: 1, count: 1 },
            { hour: 6, count: 1 },
        ],
    },
];

需求

  • 对比hours数组,为每个inParkings中未包含的hours时段添加count:0的条目
  • 保留原有的所有inParkings数据(包括不在hours范围内的条目,比如Y中的hour:1)
  • 最终的data数组需按hour从小到大排序

用户现有代码

data.map((m) => {
    return {
        name: m.title,
        data: m.inParkings.slice().sort((a, b) => {
            return a.hour - b.hour;
        }),
    };
})

完善后的代码

const result = data.map(item => {
    // 将原inParkings转换为hour为键的映射表,快速查找已有时段
    const parkingMap = item.inParkings.reduce((acc, parking) => {
        acc[parking.hour] = parking.count;
        return acc;
    }, {});

    // 补全hours数组中缺失的时段,count设为0
    hours.forEach(hour => {
        if (!parkingMap.hasOwnProperty(hour)) {
            parkingMap[hour] = 0;
        }
    });

    // 将映射表转回数组,保留所有时段并按hour排序
    const fullData = Object.entries(parkingMap)
        .map(([hour, count]) => ({ hour: Number(hour), count }))
        .sort((a, b) => a.hour - b.hour);

    return {
        name: item.title,
        data: fullData
    };
});

console.log(result);

代码说明

  1. 构建映射表:用reduce把原inParkings转成键为hour、值为count的对象,将判断时段是否存在的时间复杂度从O(n)降到O(1)
  2. 补全缺失时段:遍历hours数组,将不存在的时段以count:0的形式添加到映射表中
  3. 转换并排序:把映射表转回数组,将hour字符串转为数字类型后,按hour从小到大排序
  4. 返回结果:返回包含name(原title)和完整排序后data的对象

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 16:05:34