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
Just cycle through the array, and keep track of the max as you go:
function getMax(arr, prop) {
var max;
for (var i=0 ; i parseInt(max[prop]))
max = arr[i];
}
return max;
}
Usage is like:
var maxPpg = getMax(arr, "ppg");
console.log(maxPpg.player + " - " + maxPpg.team);
Fiddle demo
Edit
You can also use the Javascript "sort" method to get the top n values:
function getTopN(arr, prop, n) {
// clone before sorting, to preserve the original array
var clone = arr.slice(0);
// sort descending
clone.sort(function(x, y) {
if (x[prop] == y[prop]) return 0;
else if (parseInt(x[prop]) < parseInt(y[prop])) return 1;
else return -1;
});
return clone.slice(0, n || 1);
}
Usage:
var topScorers = getTopN(arr, "ppg", 2);
topScorers.forEach(function(item, index) {
console.log("#" + (index+1) + ": " + item.player);
});
Fiddle demo