How to find the largest value of an array in an arraylist in JavaScript
I have an array with elements in the following format. I tried, I collected everything edtime
and put them in edtimearray
. I am trying to find the largest among the array values. I used something like this. but I get the message "the object does not support this action".
var edtimearray = [];
for (var i = 0; i <= obj.length - 1; i++) {
edtimearray = obj[i].edtime;
if (i == obj.length - 1) {
var arrayMax = Function.prototype.apply.bind(Math.max, edtimearray);
}
}
source to share
I think you can simplify this:
var max = Math.max.apply(Math, obj.map(function(o) { return o.edtime; }));
So, you start with an array of objects, and you want to get an array of property values from those objects. JavaScript (unfortunately) does not have a standard "curl" method, so you use .map()
these property values to construct an array.
Now what you want to do is call Math.max()
with these property values as arguments like
var max = Math.max(value1, value2, ... )
What's included .apply()
. When you need a list of arguments but you have an array, .apply()
is your friend. So we just need to call Math.max()
with .apply()
- and pass in Math
as a value this
, because some native functions are picky about this - and then an array as the second argument.
source to share