I\'m trying to create a JavaScript function which takes information from an array in an external JSON and then takes the max value (or the top 5 values) for one of the JSON
I found the following approach very neat:
arr.sort(
function(a, b) {
return parseFloat(b['ppg']) - parseFloat(a['ppg']);
}
)[0]['player']
Demo in snippet:
var arr =[
{
"player" : "Andre Drummond",
"team" : "Detroit Pistons",
"ppg" : "15.4",
"rpg" : "11.6",
"apg" : "2.4",
"bpg" : "1.6",
"spg" : "0.8",
"3pg" : "0.1"
},
{
"player" : "Anthony Davis",
"team" : "New Orleans Pelicans",
"ppg" : "16.4",
"rpg" : "13.6",
"apg" : "2.6",
"bpg" : "3.5",
"spg" : "1.2",
"3pg" : "0.1"
},
{
"player" : "Carmelo Anthony",
"team" : "New York Knicks",
"ppg" : "27.4",
"rpg" : "5.4",
"apg" : "4.5",
"bpg" : "1.1",
"spg" : "1.5",
"3pg" : "1.6"
}
]
console.log(
arr.sort(
function(a, b) {
return parseFloat(b['ppg']) - parseFloat(a['ppg']);
}
)[0]['player']
);
First, I sort the array in descending order, then I choose the first element which contains the max value. In the code, I found the player who has the max ppg value. Hope this helps!