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

如何用JavaScript获取JSON数组中最大值对应的索引与ID

获取JSON数组中最大值对应的索引与ID

你现有的代码只能单独拿到最大值,要同时获取对应索引和ID,这里提供两种实用方法:

方法一:用reduce一次遍历完成(推荐)

reduce可以在计算最大值的同时,同步跟踪对应的索引和ID,只需要把累加器设置为包含这些信息的对象,一次遍历就能拿到所有结果,效率更高:

const shots = [{
    id: 1,
    amount: 2
  },
  {
    id: 2,
    amount: 4
  },
  {
    id: 3,
    amount: 52
  },
  {
    id: 4,
    amount: 36
  },
  {
    id: 5,
    amount: 13
  },
  {
    id: 6,
    amount: 33
  }
];

const result = shots.reduce((acc, shot, index) => {
  if (shot.amount > acc.maxAmount) {
    return {
      maxAmount: shot.amount,
      index: index,
      id: shot.id
    };
  }
  return acc;
}, { maxAmount: -Infinity, index: -1, id: -1 });

console.log(result);
// 输出:{ maxAmount: 52, index: 2, id: 3 }

初始化时把累加器的maxAmount设为负无穷,确保第一个元素能被正常选中。遍历过程中,只要当前元素的amount比累加器里的最大值大,就更新所有关联信息,否则保持原累加器状态。

方法二:先找最大值,再匹配对应元素

如果觉得reduce逻辑稍复杂,可以分两步走:先拿到最大值,再用findIndex和find定位对应元素:

const shots = [{/* 数据同上 */}];

// 第一步:获取最大值
const highestAmount = Math.max.apply(Math, shots.map(o => o.amount));
// 第二步:获取对应索引
const highestIndex = shots.findIndex(shot => shot.amount === highestAmount);
// 第三步:获取对应ID
const highestId = shots.find(shot => shot.amount === highestAmount).id;

console.log('最大值:', highestAmount); // 52
console.log('索引:', highestIndex); // 2
console.log('ID:', highestId); // 3

注意:如果数组中有多个元素的amount等于最大值,findIndex和find都会返回第一个匹配的结果,根据你的实际需求调整即可。

适配你的视频场景

你需要找最高比特率的视频地址,只需要把代码里的amount替换成比特率字段(比如bitrate),id替换成视频地址字段(比如videoUrl),逻辑完全通用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 19:45:50