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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.