简体   繁体   中英

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.

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];
                                        }));
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);
var t=plottingPoints[0];
$(plottingPoints  ).each (function (i,n){

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

});

now , t[1] - is your answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM