Getting max value(s) in JSON array

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<arr.length ; i++) {
        if (max == null || parseInt(arr[i][prop]) > 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

Leave a Comment