Daniela costina Vaduva
Daniela costina Vaduva

Reputation: 1897

Get the biggest value from a JavaScript multidimensional-array

I have the following variable:

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]"

send to me by a php script. I do the following operations on it:

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

to obtain the desired form (for further scopes) which is a multidimensional-array. How it is possible in JavaScript to iterate through it and get the biggest value (in the above example I think is 46631) and also the corresponding date (ex. 2013-05-10)? Here is an example on jsfiddle: http://jsfiddle.net/DanielaVaduva/PYEhK/

Upvotes: 1

Views: 881

Answers (3)

georg
georg

Reputation: 215059

I've got this function:

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

Usage:

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

In your example:

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

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

Upvotes: 1

Mark Walters
Mark Walters

Reputation: 12400

If response is indeed a multidimensional array then this would work, i'm sure there is a neater or more efficient way of achieving this but this should be a push in the right direction

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

Upvotes: 1

bingjie2680
bingjie2680

Reputation: 7773

I would recommend to use Underscore library, then it is easy to find a max :

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

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

Here is the code..

Upvotes: 2

Related Questions