Reputation: 10491
First, here's a quick snippet of the data I'm working with:
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}
]
Simple enough, I am trying to grab the n'th largest value from the stat key's values in myData, and then filter myData to include only the n objects where the stat key's value is greater than or equal to the n'th largest value. I am not too worried about how ties are handled (ie. if there is more than one value tied for n'th largest...
Still getting my feet wet with javascript, so any help with these data manip tasks are greatly appreciated, thanks!
Upvotes: 0
Views: 66
Reputation: 2156
Use it like this:
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);
}
Edited to make shorter thanks to @ibrahimmahrir
Upvotes: 1