Velocity Reviews > Question about Math.min()

Yansky
Guest
Posts: n/a

 05-31-2007
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.

Pete
Guest
Posts: n/a

 06-01-2007
On Jun 1, 7:49 am, Yansky <thegoodd...@gmail.com> wrote:
> 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.

Douglas Crockford
Guest
Posts: n/a

 06-01-2007
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/

Pete
Guest
Posts: n/a

 06-01-2007

>
> Math.min.apply(Math, tempArray)
>

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

RobG
Guest
Posts: n/a

 06-01-2007
On Jun 1, 5:19 pm, Pete <peter.gal...@gmail.com> wrote:
> > 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;

--
Rob