Good day everyone!
I've found this great code from this site:
var points = [30,100];
document.getElementById("demo").innerHTML = myArrayMax(points);
function myArrayMax(arr) {
var len = arr.length;
var max = -Infinity;
while (len--) {
if (arr[len] > max) {
max = arr[len];
}
}
return max;
}
source: Find the min/max element of an Array in JavaScript
It really works really well and very fast. I've got a question (out of curiosity). When I tried to add (or manipulate) something, the result didn't match based from the first code. Here is the code:
var points = [30,100];
document.getElementById("demo").innerHTML = myArrayMax(points);
function myArrayMax(arr) {
var len = arr.length;
var max = -Infinity;
while (len--) {
if (arr[len-1] > max) {
max = arr[len-1];
}
}
return max;
}
I've assumed that the array[0]
is the first array element, also I used post-decrement function, and yet I didn't get the expected result.