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

高效筛选数组嵌套对象内得分等于1的队伍的实现方法

解决方案

核心思路

  • 最优时间复杂度为O(n)(n为比赛总场数),仅需单次遍历所有比赛记录即可完成筛选,无冗余计算
  • 每场比赛直接判断参赛队伍的得分,将得分=1的队伍直接存入结果集,避免多次遍历数组浪费性能

实现代码

最简实现(已知每场固定为2支队伍,字段为team1、team2)

const getWinningTeams = (matches) => {
  const winners = []
  for (const match of matches) {
    if (match.team1.score === 1) winners.push(match.team1)
    if (match.team2.score === 1) winners.push(match.team2)
  }
  return winners
}

// 调用示例
const winningTeams = getWinningTeams(latestMatchesArray)

通用实现(支持后续扩展单场多支队伍的场景,性能一致)

const getWinningTeams = (matches) => {
  const winners = []
  for (const match of matches) {
    // 自动读取当前场次所有队伍对象,无需手动枚举字段
    const allTeams = Object.values(match)
    allTeams.forEach(team => {
      if (team.score === 1) winners.push(team)
    })
  }
  return winners
}

运行结果

使用你提供的示例数据调用后,返回结果如下:

[
  { team_id: '1234', teamName: 'abc 101', score: 1 },
  { team_id: '4321', teamName: 'cba 101', score: 1 }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 06:45:07