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

JS对比对象points值 新增isHighest最高值标识实现方案

问题根因

原有实现的判断逻辑存在缺陷:

  • 遍历第一个元素(索引0)时,scoreTeams[idx - 1]?.points取值为undefined,任何数值和undefined做>比较都会返回false,因此第一个元素无论分数多高,永远会被标记为isHighest: false
  • 遍历第二个元素时,仅判断当前值是否大于前一个元素值,没有覆盖「最高值出现在第一个位置」的场景,因此当第一个队伍分数更高时,两个元素都会被错误标记为false。
实现方案

核心逻辑是先获取整个数组中的最高分数值,再逐一对每个队伍的分数和最高值做相等判断,该逻辑支持任意长度的队伍数组,不局限于2个队伍的场景,也能兼容多队并列最高分的情况。

符合reduce写法要求的实现

const newTeams = scoreTeams.reduce((acc, team, idx, arr) => {
  // 首次循环时计算一次最高分,避免重复计算
  if (idx === 0) {
    acc.maxPoints = Math.max(...arr.map(t => t.points))
  }
  acc.result.push({
    ...team,
    isHighest: team.points === acc.maxPoints
  })
  return acc
}, { result: [], maxPoints: 0 }).result

更简洁易读的实现(推荐)

不需要强行套用reduce,用map实现逻辑更直观,性能也更优:

// 先计算全局最高分
const maxPoints = Math.max(...scoreTeams.map(team => team.points))
// 遍历生成带标记的新数组
const newTeams = scoreTeams.map(team => ({
  ...team,
  isHighest: team.points === maxPoints
}))
运行结果验证
  • 当队伍1分数21、队伍2分数11时,返回结果:
[
  { teamName: 'Team name 1', points: 21, isHighest: true },
  { teamName: 'Team name 2', points: 11, isHighest: false }
]
  • 当队伍1分数11、队伍2分数21时,返回结果:
[
  { teamName: 'Team name 1', points: 11, isHighest: false },
  { teamName: 'Team name 2', points: 21, isHighest: true }
]

内容的提问来源于stack exchange,提问作者Vinícius Cardoso

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 04:33:24