Getting max value(s) in JSON array

前端 未结 11 1710
醉梦人生
醉梦人生 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:39

    Simplicity thanks you in the long run.

    function getMaxValueByAttribute(arr, attr) {
        var max = "-99999999999";
        arr.forEach(function (member, index) {
                // console.log(member, index);
                if (member.hasOwnProperty(attr) && parseFloat(member[attr]) > parseFloat(max)) {
                    max = member[attr];
                    // console.log("Max now: " + max);
                }
            });
        return max;
        }
    

    Then use it like:

    var result = getMaxValueByAttribute(arr, "ppg");
    // result = "27.4"
    

提交回复
热议问题