Javascript - 获取对象数组中特定键值的第n个最大值

时间:2018-04-18 18:22:30

标签: javascript ecmascript-6

首先,这里是我正在使用的数据的快速摘录:

var myData = [
    {player: "Joe", team: "team1", stat: 15},
    {player: "Tom", team: "team3", stat: 23},
    {player: "Red", team: "team2", stat: 8},
    {player: "Smi", team: "team5", stat: 0},
    {player: "Bib", team: "team6", stat: 24},
    {player: "Cat", team: "team2", stat: 6},
    {player: "Dan", team: "team3", stat: 50},
    {player: "Jim", team: "team1", stat: 17}
]

很简单,我试图从 myData 中的 stat 键的值中获取第n个最大值,然后将myData过滤到仅包括 stat 键的值大于或等于第n个最大值的n个对象。我并不太担心如何处理关系(即,如果有多个值与第n个最大值相关联......

仍然用javascript弄湿我的脚,所以对这些数据操作任务的任何帮助都非常感谢,谢谢!

1 个答案:

答案 0 :(得分:1)

像这样使用:

ReturnHigherFrom(2) //Returns 2 with most higher stats



var myData = [
    {player: "Joe", team: "team1", stat: 15},
    {player: "Tom", team: "team3", stat: 23},
    {player: "Red", team: "team2", stat: 8},
    {player: "Smi", team: "team5", stat: 0},
    {player: "Bib", team: "team6", stat: 24},
    {player: "Cat", team: "team2", stat: 6},
    {player: "Dan", team: "team3", stat: 50},
    {player: "Jim", team: "team1", stat: 17}
];

console.log(ReturnHigherFrom(3));

function ReturnHigherFrom(nth){
    return myData.sort((a, b) => b.stat - a.stat).slice(0, nth);
}




编辑以更简短地感谢@ibrahimmahrir