program for finding maximum n minimum in javascript arrays?

clerkman1612

Journeyman
I want to know about a program which find itself the maximum and minimum numbers in data of arrays(JavaScript)?:unsure: I m using adobe dreamweaver.
I m very confused. Plz tell me.
take example
var a = new Array
a[0]=1
a[1]=2
a[2]=3
a[3]=4
a[4]=5

now here we have to find what is maximum and mininum no in this arrays?
Obviously answer is 5 and 1 respectively.
Thanks in Advance:reading:
 

krishnandu.sarkar

Simply a DIGITian
Staff member
Code:
Array.prototype.max = function() {
var max = this[0];
var len = this.length;
for (var i = 1; i < len; i++) if (this[i] > max) max = this[i];
return max;
}

Array.prototype.min = function() {
var min = this[0];
var len = this.length;
for (var i = 1; i < len; i++) if (this[i] < min) min = this[i];
return min;
}

OR

Code:
Array.prototype.max = function(){
	return Math.max.apply({},this)
}

Array.prototype.min = function(){
	return Math.min.apply({},this)
}

Call the functions using...
Code:
alert(a.max());
where a is your array...
 
Top Bottom