小编典典

在JSON数组中获取最大值

json

我正在尝试创建一个JavaScript函数,该函数从外部JSON中的数组获取信息,然后为JSON变量之一获取最大值(或前5个值)。对于此示例,假设我要获取值“
ppg”的最大值。这是数组的一个小示例:

[
{
    "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"
}
]

遍历数组以获取最大值,然后从该值获取“玩家”和“团队”值的最佳方法是什么?该页面将是交互式的,因为我将具有一个下拉菜单栏,允许查看者在“玩家”和“团队”之外的六个JSON值之一之间进行选择。提前致谢!


阅读 1545

收藏
2020-07-27

共1个答案

小编典典

只是循环遍历数组,并在执行过程中跟踪最大值:

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;
}

用法就像:

var maxPpg = getMax(arr, "ppg");
console.log(maxPpg.player + " - " + maxPpg.team);

小提琴演示

编辑

您还可以使用Javascript的“ sort”方法获取前n个值:

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);
}

用法:

var topScorers = getTopN(arr, "ppg", 2);
topScorers.forEach(function(item, index) {
    console.log("#" + (index+1) + ": " + item.player);
});

小提琴演示

2020-07-27