1

我有以下变量:

response = "['2013-04-20', 10568]", "['2013-04-21', 4566]", "['2013-04-22', 14228]", "['2013-04-23', 5056]", "['2013-04-24', 25837]", "['2013-04-25', 39723]", "['2013-04-26', 37297]", "['2013-04-27', 23482]", "['2013-04-28', 31371]", "['2013-04-29', 25088]", "['2013-04-30', 27726]", "['2013-05-01', 26287]", "['2013-05-02', 15988]", "['2013-05-03', 34628]", "['2013-05-04', 13415]", "['2013-05-05', 24566]", "['2013-05-06', 33443]", "['2013-05-07', 15676]", "['2013-05-08', 18143]", "['2013-05-09', 28611]", "['2013-05-10', 46631]", "['2013-05-11', 24315]", "['2013-05-12', 15183]", "['2013-05-13', 13154]", "['2013-05-14', 9185]"

通过 php 脚本发送给我。我对其进行以下操作:

var organicJson = response.replace(/"/g,'');
organicJson = "[" + organicJson + "]";
organicJson = organicJson.replace(/'/g,'"');
var myOrganicData = JSON.parse(organicJson);

获得所需的形式(用于进一步的范围),它是一个多维数组。如何在 JavaScript 中迭代它并获得最大值(在上面的示例中,我认为是 46631)以及相应的日期(例如 2013-05-10)?这是关于 jsfiddle 的示例:http: //jsfiddle.net/DanielaVaduva/PYEhK/

4

3 回答 3

2

我建议使用Underscore库,然后很容易找到一个 max :

var m = _.max(myOrganicData, function(item){
   return item[1];
})

alert(m); 
alert(m[1]); 

这是代码..

于 2013-05-20T11:36:30.827 回答
1

我有这个功能:

function maxBy(array, fn) {
    return array.map(function(x) {
        return [x, fn(x)]
    }).reduce(function(max, x) {
        return x[1] > max[1] ? x : max
    })[0]
}

用法:

 maxItem = maxBy(array, function-to-return-a-property)

在您的示例中:

 maxItem = maxBy(myOrganicData, function(x) { return x[1] })

http://jsfiddle.net/PYEhK/2/

于 2013-05-20T12:04:03.320 回答
1

如果响应确实是一个多维数组,那么这将起作用,我相信有一种更简洁或更有效的方法来实现这一点,但这应该是朝着正确方向的推动

var response = [['2013-04-20', 10568], ['2013-04-21', 4566], ['2013-04-22', 14228], ['2013-04-23', 5056], ['2013-04-24', 25837]];

function returnLargest(multiArr){
  var lastNum, output = [];

  for(var i=0; i<multiArr.length; i++){ 
    if(!lastNum){ 
       lastNum = multiArr[i][1];
       output[0] = multiArr[i][0]; 
    } else if(lastNum < multiArr[i][1]){
      lastNum = multiArr[i][1];
      output[0] = multiArr[i][0];
    }
  }
  output.push(lastNum);
  return output;  //In this case ['2013-04-24', 25837] 
}
于 2013-05-20T11:55:57.337 回答