获取JSON数组中的最大值

时间:2014-04-08 22:40:47

标签: javascript jquery arrays 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"
}
]

通过数组获取最大值然后获取值"播放器"的最佳方法是什么?和#34;团队"从这个价值?该页面将是交互式的,因为我将有一个下拉菜单栏,允许查看者在除#34;播放器"之外的六个JSON值之一中进行选择。和"团队"。提前谢谢!

11 个答案:

答案 0 :(得分:14)

只需在数组中循环,并随时跟踪最大值:

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

Fiddle demo

修改

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

Fiddle demo

答案 1 :(得分:2)

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

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']
);

首先我对数组进行降序排序,然后选择包含最大值的第一个元素。在代码中,我发现播放器的最大值 ppg 。希望这有帮助!

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

这适合我。

答案 3 :(得分:1)

这应该有效:

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

答案 4 :(得分:1)

您可能会发现此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

答案 5 :(得分:0)

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

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

  

data =&gt;是数组

     

stat =&gt;是您要按

排序的统计数据      

info =&gt;是要返回的属性数组。

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"
// }

答案 6 :(得分:0)

正在寻找具有特定属性'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;
}

用法:

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

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

答案 7 :(得分:0)

从长远来看,简单的谢谢你。

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

然后使用它:

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

答案 8 :(得分:0)

您可以轻松实现 lodash

# you could use this in place of `m[ m == "NA" ] <- ""`
for (i in seq_len(nrow(m))) {
  for (j in seq_len(ncol(m))) {
    if (m[i,j] == "NA") m[i,j] == ""
  }
}
var players = [{
    "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"
  }
];

var topscorer = _
  .chain(players)
  .sortBy('ppg')
  .reverse()
  .map(function(o) {
    return 'Top scorer: ' + o.player + ' - ' + o.team;
  })
  .head()
  .value();

console.log(topscorer);

或更短:

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.core.min.js"></script>
var players = [{
    "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(_.maxBy(players, 'ppg').player);

答案 9 :(得分:0)

我的解决方案在这里。请记住使用==而非===来比较数字和字符串。

const getMax = (arr, prop) => {
  const tmp = arr.map(x => x[prop]);
  const max = Math.max(...tmp);
  return arr.filter(x => x[prop] == max);
}

getMax(myArr,"bpg")

单行版本:

myArr.filter( x => x["bpg"] == Math.max(...myArr.map(x => x["bpg"])) )

答案 10 :(得分:0)

更简单:

const players =                                           
  [ { 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' } 
  ] 

const getPlayerMax_on = cod => players.reduce((a,c)=>((+a[cod])<(+c[cod]))?c:a)

const maxOn_ppg = getPlayerMax_on('ppg')

console.log( maxOn_ppg.player, maxOn_ppg.team, maxOn_ppg.ppg )