0

I am trying to get the maximum value in an array but when I try to display it I get every value from that array.

for (var ii = 0; ii < items.length; ii++) {
				var myArray = [items[ii].odoEnd];
				var highestEnd = (Math.max.apply(Math,myArray));
			
                $("#trips").append("<li>" + items[ii].TripDate + " : " + items[ii].AKTripContact + "<br/>" +
				items[ii].Comments + "<br/>" +
				"Odometer: " + items[ii].odoStart + 
				" to " + items[ii].odoEnd +
				"@" + items[ii].Rate + "/km" + "<br/>" +
				items[ii].business + " : " + items[ii].Distance + "km : $" + items[ii].Amount + "</li>");
				
				alert(highestEnd);
            } // for

Why is my alert box giving me an alert for every value and not just the maximum?

Thanks

2
Contributors
1
Reply
3
Views
5 Years
Discussion Span
Last Post by Airshow
0

n3xtgen,

Two things are wrong.

  • var myArray = [items[ii].odoEnd]; creates a new array with a single element at each loop iteration. The following statement, var highestEnd = (Math.max.apply(Math,myArray)); then finds the highest (ie. the only) element in that array.
  • alert(highestEnd); is inside the loop.

The following should work, assuming:

  1. all .odoEnd values will be zero or greater
  2. you don't need an array of all .odoEnd; values further down in the code.
var highestEnd = 0;
for (var ii=0; ii<items.length; ii++) {
	odoEndMax = Math.max(highestEnd, items[ii].odoEnd);
	...
}
alert(highestEnd);

Airshow

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.