如何从对象数组中获取指定属性值最高的对应对象
解决方案
最优实现(时间复杂度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
相关产品推荐
相关产品推荐

