Getting max value(s) in JSON array

前端 未结 11 1687
醉梦人生
醉梦人生 2020-12-06 05:56

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

11条回答
  •  离开以前
    2020-12-06 06:34

    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

提交回复
热议问题