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

JS查找array1元素在带重复项的array2中的所有对应索引

问题原因

你原有函数只能返回第一个匹配索引,是因为逻辑中找到第一个匹配项就直接return终止遍历了,没有收集后续所有匹配的下标。


实现方案

推荐优先使用预构建索引映射的方案,只需遍历array2一次,后续查询效率为O(1),适合数据量较大的场景:

1. 先构建homeTeam对应所有索引的映射表

const teamIndexMap = {}
array2.forEach((item, index) => {
  const teamName = item.homeTeam
  // 如果球队名第一次出现,先初始化空数组存储索引
  if (!teamIndexMap[teamName]) teamIndexMap[teamName] = []
  teamIndexMap[teamName].push(index)
})

2. 遍历array1生成最终结果

const result = array1.map(item => {
  return {
    ...item,
    // 不存在匹配的球队默认返回空数组,可按需调整默认值
    IndexInArr2: teamIndexMap[item.homeTeam] || []
  }
})

简易版实现(无需提前建表)

如果数据量不大,也可以直接修改你的原有查找函数,改为收集所有匹配索引:

function findAllIndexes(array, attr, value) {
  const matchIndexes = []
  for (let i = 0; i < array.length; i++) {
    if (array[i][attr] === value) matchIndexes.push(i)
  }
  return matchIndexes
}

// 调用生成结果
const result = array1.map(item => {
  return {
    ...item,
    IndexInArr2: findAllIndexes(array2, 'homeTeam', item.homeTeam)
  }
})

注:你给出的期望输出中Gamba Osaka的索引有误,该元素在array2中的实际下标是8,运行上述代码会得到正确结果IndexInArr2: [8]。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 06:00:01