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

如何高效从驾驶员对象数组中返回目标回合的驾驶员与回合索引?

高效搜索卡丁车驾驶员参赛回合的实现方案

问题背景

我用二维数组存储卡丁车驾驶员数据,每个驾驶员对象包含round数组记录其参赛回合。需求是搜索round数组,返回包含驾驶员索引和对应回合在round数组中的索引的结果数组;由于后续数据量会很大,不想使用普通for循环,希望找到更高效的实现方式。

举个查询示例:当搜索驾驶员是否参加过第10回合时,最终结果应为[[1,4], [3,3], [5,1]],对应:

  • 索引1的驾驶员,第10回合在其round数组中的索引是4
  • 索引3的驾驶员,第10回合在其round数组中的索引是3
  • 索引5的驾驶员,第10回合在其round数组中的索引是1

原始模拟代码

driver = [];
driver[0] = [];

for(n=0; n<=5; n++){
    driver[0][n] = new Object();
    driver[0][n].id = "Driver: "+n;
    driver[0][n].round = new Array();
}

driver[0][0].round = [0];
driver[0][1].round = [1,3,5,7,10];
driver[0][2].round = [1,2,4];
driver[0][3].round = [5,7,8,10,12,14];
driver[0][4].round = [6,11,12];
driver[0][5].round = [4,10,11,12];

高效实现方案

方案1:使用数组内置高阶函数(Filter + Map + IndexOf)

引擎对数组内置方法有底层优化,性能优于手写普通for循环,写法也更简洁。

const targetRound = 10;
const result = driver[0]
  .map((driverItem, driverIdx) => {
    const roundIndex = driverItem.round.indexOf(targetRound);
    return roundIndex !== -1 ? [driverIdx, roundIndex] : null;
  })
  .filter(item => item !== null);

console.log(result); // 输出 [[1,4], [3,3], [5,1]]

逻辑说明:

  1. map遍历每个驾驶员,用indexOf快速查找目标回合在round数组中的位置
  2. 找到则返回[驾驶员索引, 回合索引],否则返回null
  3. filter过滤掉无效的null值,得到最终结果

方案2:预处理建立哈希索引(适合多次查询场景)

如果需要频繁查询不同回合,提前将每个驾驶员的round数组转换为Map结构,后续查询可实现O(1)时间复杂度,是大数据量下的最优解。

// 仅需预处理一次
driver[0].forEach(driverItem => {
  driverItem.roundMap = new Map();
  driverItem.round.forEach((roundNum, roundIdx) => {
    driverItem.roundMap.set(roundNum, roundIdx);
  });
});

// 任意次数查询目标回合
const targetRound = 10;
const result = driver[0]
  .map((driverItem, driverIdx) => {
    const roundIndex = driverItem.roundMap.get(targetRound);
    return roundIndex !== undefined ? [driverIdx, roundIndex] : null;
  })
  .filter(item => item !== null);

console.log(result); // 输出 [[1,4], [3,3], [5,1]]

逻辑说明:

  1. 预处理阶段将每个驾驶员的回合数与对应索引存入Map
  2. 查询时直接通过Map.get()获取索引,无需重复遍历round数组
  3. 一次预处理,多次查询复用,极大提升高频查询场景的性能

方案3:Web Workers(超大数据量场景)

若数据量达到百万级以上,主线程处理会阻塞页面交互,可使用Web Workers在后台线程执行搜索逻辑,避免页面卡顿。该方案适合极端大数据量场景,一般前两种方案足以覆盖大多数需求。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 23:07:46