Getting max value(s) in JSON array

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

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

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

    data => is the array

    stat => is the stat you want to sort by

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

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

提交回复
热议问题