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

Node.js:构建含唯一城市-运营商ID对的日期映射及代码修复

解决方案:实现CityId-OperatorId对去重并构建日期映射

问题根源

你原代码中使用Set存储[cityId, operatorId]数组,但数组是引用类型——即使两个数组内容完全一致,只要是不同实例,Set就会判定为不同元素,导致去重失效。

修改后的代码

下面是修复后的代码,核心思路是用字符串作为唯一标识存入Set,确保内容相同的城市-运营商对能被正确去重:

// 注意:函数需标记为async,因内部使用await调用异步服务
async function buildCityOperatorMap(data) {
  let busRecordsCityOprHash = {};
  
  for (let currentRow of data) {
    const travelDate = currentRow['Travel Date'];
    const busNumber = currentRow['Bus Number'];

    let operatorId, cityId;
    const busDetails = await busDayWiseService.getOperatorAndCityIdOfBus({
      filter: {
        busNumber: busNumber.toUpperCase(),
        fromDate: getZeroTimeDate(travelDate)
      }
    });
    
    if (busDetails) {
      operatorId = busDetails.operatorId;
      cityId = busDetails.cityId;
    }

    // 跳过无有效ID的记录,避免存入无效数据
    if (!cityId || !operatorId) continue;

    // 用字符串作为唯一键,解决引用类型无法去重的问题
    const pairKey = `${cityId}-${operatorId}`;
    if (!busRecordsCityOprHash[travelDate]) {
      busRecordsCityOprHash[travelDate] = new Set();
    }
    busRecordsCityOprHash[travelDate].add(pairKey);
  }

  // 将Set转换为你需要的数组格式(可选择数组或对象形式)
  Object.keys(busRecordsCityOprHash).forEach(date => {
    busRecordsCityOprHash[date] = Array.from(busRecordsCityOprHash[date]).map(key => {
      const [cityId, operatorId] = key.split('-').map(Number);
      // 若需要对象格式,替换为:return { cityId, operatorId };
      return [cityId, operatorId];
    });
  });

  return busRecordsCityOprHash;
}

遍历修改后的映射结构

1. 遍历所有日期及对应唯一对

// 调用函数获取结果(需在async环境中执行)
const resultMap = await buildCityOperatorMap(yourDataArray);

// 遍历每个日期
for (const [date, pairs] of Object.entries(resultMap)) {
  console.log(`日期:${date}`);
  // 遍历该日期下的所有城市-运营商对
  pairs.forEach(pair => {
    // 数组格式的输出
    console.log(`cityId: ${pair[0]}, operatorId: ${pair[1]}`);
    // 若使用对象格式,改为:console.log(`cityId: ${pair.cityId}, operatorId: ${pair.operatorId}`);
  });
}

2. 获取指定日期的唯一对

const targetDate = "2023-04-02";
const targetPairs = resultMap[targetDate];
if (targetPairs) {
  targetPairs.forEach(pair => console.log(pair));
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 12:19:53