获取JSON数组中的最大值

时间:2023-01-26 14:38:23

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:

我正在尝试创建一个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"
}
]

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!

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

8 个解决方案

#1


12  

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

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:

您还可以使用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);
}

Usage:

用法:

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

Fiddle demo

小提琴演示

#2


2  

function getMaxOfJson(jsonalreadyparsed, property) {
    var max = null;
    for (var i=0 ; i<jsonalreadyparsed.length ; i++) {

            if(max == null){

                max = jsonalreadyparsed[i][property];

            } else {

            if (parseFloat(jsonalreadyparsed[i][property]) > max){

                max = jsonalreadyparsed[i][property];

            }

        }

    }
    return max;
}

This works for me.

这对我有用。

#3


1  

You might find this sortByAttribute function useful. Just pass in the attribute by string you're looking to sort it by, and it'll return whatever object has the max value for the specific attribute you're looking for. It'll still return the whole array, just sorted ascending by the property you specified.

您可能会发现此sortByAttribute函数很有用。只需按字符串传递属性即可对其进行排序,并且它将返回任何具有您正在查找的特定属性的最大值的对象。它仍将返回整个数组,只是按您指定的属性进行升序排序。

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


function sortByAttribue(arr, attribute) {
  return arr.sort(function(a,b) { 
    return a[attribute] < b[attribute];
  });
}

sortByAttribue(myArr, "3pg") // returns Carmelo Anthony first
sortByAttribue(myArr, "bpg") // returns Anthony Davis first

#4


1  

This should work:

这应该工作:

var highestValue = 0; //keep track of highest value

//loop through array of objects
for (var i=0, len = ary.length; i<len; i++) {
  var value = Number(ary[i]["ppg"]);
  if (value > highestValue) {
      highestValue = value;
  }
}

#5


1  

I found the following approach very neat:

我发现以下方法非常简洁:

var arr =[
{
    "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"
}
]
console.log(
arr.sort( 
    function(a, b) {
       return parseFloat(b['ppg']) - parseFloat(a['ppg']);
    }
    )[0]['player']
);

First I sort the array descending, then I choose the first element which contains the max value. In the code, I found the player who has the max ppg value. Hope this helps!

首先我对数组进行降序排序,然后选择包含最大值的第一个元素。在代码中,我找到了具有最大ppg值的玩家。希望这可以帮助!

#6


0  

function that's looking for item with the specific property'x maximum:

正在寻找具有特定属性'x最大值的项目的函数:

function getMax(array, propName) {
    var max = 0;
    var maxItem = null;
    for(var i=0; i<array.length; i++) {
        var item = array[i];
        if(item[propName] > max) {
            max = item[propName];
            maxItem = item;
        }
    }

    return maxItem;
}

usage:

用法:

$(document).ready(function() {
    $('#getMaxBtn').click(function() {
        var max = getMax(jsonArray, 'ppg');

        alert(max.player);
    });
});

#7


0  

This will allow you to choose what stat you want and what information you want back.

这将允许您选择您想要的统计数据以及您想要的信息。

http://jsbin.com/tudegofa/1/edit

http://jsbin.com/tudegofa/1/edit

data => is the array

data =>是数组

stat => is the stat you want to sort by

stat =>是您要排序的统计信息

info => is an array of properties you want returned.

info =>是要返回的属性数组。

function getValues (data, stat, info)
{
  var selectedValues = data.map(function(x) {
    return parseFloat(x[stat]);
  })

  var i = selectedValues.indexOf(Math.max.apply(Math, selectedValues));

  var result = {};
  info.forEach(function(x) {
      result[x] = test[i][x];
  })
  return result;
}

var myData = '';
$.getJSON('/url/to/grab/json', function(data) {

  myData = data;

});

getValues(myData, "bpg", ["player","team"]);

//[object Object] {
//  player: "Anthony Davis",
//  team: "New Orleans Pelicans"
// }

#8


0  

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"

#1


12  

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

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:

您还可以使用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);
}

Usage:

用法:

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

Fiddle demo

小提琴演示

#2


2  

function getMaxOfJson(jsonalreadyparsed, property) {
    var max = null;
    for (var i=0 ; i<jsonalreadyparsed.length ; i++) {

            if(max == null){

                max = jsonalreadyparsed[i][property];

            } else {

            if (parseFloat(jsonalreadyparsed[i][property]) > max){

                max = jsonalreadyparsed[i][property];

            }

        }

    }
    return max;
}

This works for me.

这对我有用。

#3


1  

You might find this sortByAttribute function useful. Just pass in the attribute by string you're looking to sort it by, and it'll return whatever object has the max value for the specific attribute you're looking for. It'll still return the whole array, just sorted ascending by the property you specified.

您可能会发现此sortByAttribute函数很有用。只需按字符串传递属性即可对其进行排序,并且它将返回任何具有您正在查找的特定属性的最大值的对象。它仍将返回整个数组,只是按您指定的属性进行升序排序。

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


function sortByAttribue(arr, attribute) {
  return arr.sort(function(a,b) { 
    return a[attribute] < b[attribute];
  });
}

sortByAttribue(myArr, "3pg") // returns Carmelo Anthony first
sortByAttribue(myArr, "bpg") // returns Anthony Davis first

#4


1  

This should work:

这应该工作:

var highestValue = 0; //keep track of highest value

//loop through array of objects
for (var i=0, len = ary.length; i<len; i++) {
  var value = Number(ary[i]["ppg"]);
  if (value > highestValue) {
      highestValue = value;
  }
}

#5


1  

I found the following approach very neat:

我发现以下方法非常简洁:

var arr =[
{
    "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"
}
]
console.log(
arr.sort( 
    function(a, b) {
       return parseFloat(b['ppg']) - parseFloat(a['ppg']);
    }
    )[0]['player']
);

First I sort the array descending, then I choose the first element which contains the max value. In the code, I found the player who has the max ppg value. Hope this helps!

首先我对数组进行降序排序,然后选择包含最大值的第一个元素。在代码中,我找到了具有最大ppg值的玩家。希望这可以帮助!

#6


0  

function that's looking for item with the specific property'x maximum:

正在寻找具有特定属性'x最大值的项目的函数:

function getMax(array, propName) {
    var max = 0;
    var maxItem = null;
    for(var i=0; i<array.length; i++) {
        var item = array[i];
        if(item[propName] > max) {
            max = item[propName];
            maxItem = item;
        }
    }

    return maxItem;
}

usage:

用法:

$(document).ready(function() {
    $('#getMaxBtn').click(function() {
        var max = getMax(jsonArray, 'ppg');

        alert(max.player);
    });
});

#7


0  

This will allow you to choose what stat you want and what information you want back.

这将允许您选择您想要的统计数据以及您想要的信息。

http://jsbin.com/tudegofa/1/edit

http://jsbin.com/tudegofa/1/edit

data => is the array

data =>是数组

stat => is the stat you want to sort by

stat =>是您要排序的统计信息

info => is an array of properties you want returned.

info =>是要返回的属性数组。

function getValues (data, stat, info)
{
  var selectedValues = data.map(function(x) {
    return parseFloat(x[stat]);
  })

  var i = selectedValues.indexOf(Math.max.apply(Math, selectedValues));

  var result = {};
  info.forEach(function(x) {
      result[x] = test[i][x];
  })
  return result;
}

var myData = '';
$.getJSON('/url/to/grab/json', function(data) {

  myData = data;

});

getValues(myData, "bpg", ["player","team"]);

//[object Object] {
//  player: "Anthony Davis",
//  team: "New Orleans Pelicans"
// }

#8


0  

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"