JavaScript
Article

jquery get the highest value in array for specific index

By Sam Deering

Simple jQuery code snippet to get the highest value in array for specific index value.

The Dataset.

var data = Array();
data[0] = {"apples":1, "pears":2, "oranges":3};
data[1] = {"apples":3, "pears":3, "oranges":5};
data[2] = {"apples":4, "pears":1, "oranges":6};

The function.

//get the highest value in array for specific index
//usage: getHighestVal(data,index)
//data = array
//index = index of array to analyse
function getHighestVal(data, index)
{
$.each(data, function (i,v)
{
thisVal = v[index];
max = (max < thisVal) ? thisVal : max; }); return max; } var highest = getHighestVal(data, 'apples'); console.log(highest); [/js] The Example:
So in this example, we want to get the highest value of “apple”.
highest value in array for specific index

Free Guide:

7 Habits of Successful CTOs

"What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.

  • eibod

    what about lowest? can you share?

    • http://www.urban-design.org.uk Vasilj Milošević

      Here:

      var count = $.map(data, function(data){ return data.apples; }),
      maxCount = Math.max.apply(this,count),
      minCount = Math.min.apply(this,count);

  • eibod

    what about getting the lowest value in an array? can you please share? thank you soooo much!

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.