如何为对象数组中缺失对应CITY的STATION组插入CITY对象
补全数组中缺失的CITY对象
现有两个JavaScript对象数组:
filteredArr:包含筛选后的CITY和STATION类型对象citiesData:包含所有CITY类型对象
需要实现的逻辑:遍历filteredArr,针对每个cityId对应的STATION对象组,检查该组前是否存在对应CITY对象。如果不存在,从citiesData中取出对应cityId的CITY对象,插入到该组第一个STATION对象的前面。
示例输入
筛选后的数组
const filteredArr = [ {name: "Prague - city", cityId: "111", type: "CITY"}, {name: "Prague - bus station", cityId: "111", type: "STATION"}, {name: "Prague - train station ", cityId: "111", type: "STATION"}, {name: "Brno - bus station", cityId: "333", type: "STATION"}, {name: "Brno - train station", cityId: "333", type: "STATION"}, ]
城市数据数组
const citiesData = [ {name: "Prague - city", cityId: "111", type: "CITY"}, {name: "Brno", cityId: "333", type: "CITY"}, {name: "Wien", cityId: "444", type: "CITY"} // 更多城市数据 ]
期望输出
const finalResult = [ {name: "Prague - city", cityId: "111", type: "CITY"}, {name: "Prague - bus station", cityId: "111", type: "STATION"}, {name: "Prague - train station ", cityId: "111", type: "STATION"}, {name: "Brno", cityId: "333", type: "CITY"}, // 新增的CITY对象,放在对应STATION组最前面 {name: "Brno - bus station", cityId: "333", type: "STATION"}, {name: "Brno - train station", cityId: "333", type: "STATION"} ]
解决方案
实现思路
- 将
citiesData转换为以cityId为键的映射对象,实现O(1)时间复杂度的快速查找 - 用集合记录已处理过的
cityId,避免重复添加同一CITY对象 - 遍历
filteredArr:- 遇到CITY对象直接加入结果数组,同时标记对应
cityId为已处理 - 遇到STATION对象时,先检查对应
cityId是否已处理:未处理则先从映射中取出CITY对象加入结果,再加入当前STATION对象
- 遇到CITY对象直接加入结果数组,同时标记对应
代码实现
// 构建城市数据映射,提升查找效率 const cityMap = new Map(citiesData.map(city => [city.cityId, city])); const processedCityIds = new Set(); const finalResult = []; for (const item of filteredArr) { if (item.type === 'CITY') { finalResult.push(item); processedCityIds.add(item.cityId); } else { const cityId = item.cityId; if (!processedCityIds.has(cityId)) { const targetCity = cityMap.get(cityId); if (targetCity) { finalResult.push(targetCity); processedCityIds.add(cityId); } } finalResult.push(item); } } console.log(finalResult);
代码说明
- 用
Map存储城市数据,避免每次遍历数组查找,大幅提升性能 Set记录已处理ID,确保同一城市的CITY对象只添加一次- 一次遍历完成所有处理,时间复杂度为O(n)(n为
filteredArr长度),性能高效
内容的提问来源于stack exchange,提问作者Daniel Bílek
相关产品推荐
相关产品推荐

