Sameera Thilakasiri
Sameera Thilakasiri

Reputation: 9508

Get the largest value from the array in JS or jQuery

Using flow chart lib I’m plotting a graph. Below is the x and y coordinates of the graph as an array.

var plottingPoints  = [[0, 3], [4, 8], [8, 5], [9, 23], [10, 2]];

I just need to pick largest value of the y coordinate (ie 23). Please need support of expertise.

Upvotes: 2

Views: 1101

Answers (3)

Dennis
Dennis

Reputation: 14477

var plottingPoints  = [[0, 3], [4, 8], [8, 5], [9, 23], [10, 2]];
var length = plottingPoints.length;
var maxY = -Infinity;
for(var i = 0; i < length; i++)
    maxY = Math.max(plottingPoints[i][1], maxY);

Upvotes: 2

pimvdb
pimvdb

Reputation: 154838

In new browsers you can make use of ES5's .map method of arrays. Also, Math.max returns the highest value of all arguments:

// calculate max value of an array of numbers
Math.max.apply(null, plottingPoints.map(function(element) {
                                            // return y coordinate
                                            return element[1];
                                        }));

Upvotes: 2

Royi Namir
Royi Namir

Reputation: 148524

var t=plottingPoints[0];
$(plottingPoints  ).each (function (i,n){

if (n[1]>t[1]) t=n;

});

now , t[1] - is your answer

Upvotes: 1

Related Questions