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

如何从对象数组中获取指定属性值最高的对应对象

解决方案

最优实现(时间复杂度O(n),仅遍历1次)

推荐使用Array.reduce()实现,性能最好,尤其适合大体积数组:

// 示例数组
const playerList = [
  { plName: "player1", plNumber: 1, score: 30 },
  { plName: "player2", plNumber: 2, score: 24 },
  { plName: "player3", plNumber: 3, score: 89 }
];

// 直接获取最高分对象
const highestScorePlayer = playerList.reduce((maxObj, currObj) => {
  return currObj.score > maxObj.score ? currObj : maxObj;
}, playerList[0]);

如果需要同时获取该对象在数组中的索引,可调整为:

const highestScoreInfo = playerList.reduce((result, currObj, index) => {
  return currObj.score > result.player.score ? { index, player: currObj } : result;
}, { index: 0, player: playerList[0] });
// 输出结果:{ index: 2, player: { plName: "player3", plNumber: 3, score: 89 } }

其他可选实现(仅适合小数组)

如果数组体积很小,也可以用Math.max+find的组合,写法更直观,但会遍历2次数组,时间复杂度更高:

const maxScore = Math.max(...playerList.map(item => item.score));
const highestScorePlayer = playerList.find(item => item.score === maxScore);

多最高分场景处理

如果存在多个对象的score同为最高值,需要返回所有符合条件的对象,可使用filter:

const maxScore = Math.max(...playerList.map(item => item.score));
const allHighestPlayers = playerList.filter(item => item.score === maxScore);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 02:36:02