在获取JSON数组最大值(S) [英] Getting max value(s) in JSON array

查看:1962
本文介绍了在获取JSON数组最大值(S)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个JavaScript函数从外部JSON阵列需要的信息,然后花费的JSON变量之一的最大值(或前5个值)。在这个例子中,假设我想要得到的值PPG的最大值。这里是数组的一个小样本:

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 variables. For this example, let's say I want to get the max value for the value "ppg". Here is a small sample of the array:

[
{
    "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值之一之间选择除了运动员和团队。在此先感谢!

What would be the best way to go through the array to get the max value and then get the values "player" and "team" from this value? The page will be interactive, as I will have a drop-down menu bar with allows the viewer to choose between one of the six JSON values aside from "player" and "team". Thanks in advance!

推荐答案

通过数组只是周期,并跟踪最大的,当您去:

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 || parseInt(arr[i][prop]) > parseInt(max[prop]))
            max = arr[i];
    }
    return max;
}

用法是这样的:

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

小提琴演示

修改

您还可以使用JavaScript <一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort\">\"sort\"方法来获取前n值:

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

用法:

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

小提琴演示

这篇关于在获取JSON数组最大值(S)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆