By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,382 Members | 1,971 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,382 IT Pros & Developers. It's quick & easy.

Question about Math.min()

P: n/a
Hi, just a quick question about the Math.min() function.

If I have an array of numbers:

var tempArray = [12,45,2,67,86];

how come Math.min() can't look at all the numbers in the array at
once? i.e. - If I put all of the numbers in the array like so:

Math.min(12,45,2,67,86)

I get the lowest number, but when I try this:

Math.min(tempArray)

I get an error of NaN.
Cheers.

May 31 '07 #1
Share this Question
Share on Google+
4 Replies


P: n/a
On Jun 1, 7:49 am, Yansky <thegoodd...@gmail.comwrote:
Hi, just a quick question about the Math.min() function.

If I have an array of numbers:

var tempArray = [12,45,2,67,86];

how come Math.min() can't look at all the numbers in the array at
once? i.e. - If I put all of the numbers in the array like so:

Math.min(12,45,2,67,86)

I get the lowest number, but when I try this:

Math.min(tempArray)

I get an error of NaN.

Cheers.
Math.min only accepts 2 or more numbers. It won't accept an array.

Jun 1 '07 #2

P: n/a
Yansky wrote:
If I have an array of numbers:

var tempArray = [12,45,2,67,86];

how come Math.min() can't look at all the numbers in the array at
once? i.e. - If I put all of the numbers in the array like so:

Math.min(12,45,2,67,86)

I get the lowest number, but when I try this:

Math.min(tempArray)

I get an error of NaN.
Math.min.apply(Math, tempArray)

http://javascript.crockford.com/
Jun 1 '07 #3

P: n/a
>
Math.min.apply(Math, tempArray)

works fine if your array doesn't have any undefined items.

Jun 1 '07 #4

P: n/a
On Jun 1, 5:19 pm, Pete <peter.gal...@gmail.comwrote:
Math.min.apply(Math, tempArray)

works fine if your array doesn't have any undefined items.
If you have a sparse array and you know that there are no null values
(i.e. all the gaps are undefined) then copy the array, do a numeric
sort and get the value at index 0:

function asNum(a, b) { return a-b; }

function getMin(a) {
var b = a.concat()
return b.sort(asNum)[0];
}

var a = [];
a[500] = 13;
a[1000] = 0;
a[250] = 10;

alert(getMin(a));
--
Rob

Jun 1 '07 #5

This discussion thread is closed

Replies have been disabled for this discussion.