7

This is what I tried:

Math.min([1,2,3])

But only get NaN...

6 Answers 6

10

use apply:

Math.min.apply(null,[1,2,3]); //=> 1

From devguru:

Function.apply(thisArg[, argArray]) the apply method allows you to call a function and specify what the keyword this will refer to within the context of that function. The thisArg argument should be an object. Within the context of the function being called, this will refer to thisArg. The second argument to the apply method is an array. The elements of this array will be passed as the arguments to the function being called. The argArray parameter can be either an array literal or the deprecated arguments property of a function.

In this case the first argument is of no importance (hence: null), the second is, because the array is passed as arguments to Math.min. So that's the 'trick' used here.

[edit nov. 2020] This answer is rather old. Nowadays (with Es20xx) you can use the spread syntax to spread an array to arguments for Math.min.

Math.min(...[1,2,3]);
Sign up to request clarification or add additional context in comments.

Comments

3

Use JS spread operator to avoid extra coding:

console.log(Math.min(...[1,2,3]))

Comments

2

You have to iterate through the array. AFAIK there is no array_min in JS.

var i, min = arr[0];
for (i=1; i<arr.length; i++)
    min = Math.min(min, arr[i]);

Comments

1
Math.min(1, 2, 3)
1

Since, [1,2,3] cannot be converted to a number, it returns NaN.

More: Mozilla Reference

Comments

1

Use this

Array.min = function( array ){
        return Math.min.apply( Math, array );
    }; 

Check this link out - http://ejohn.org/blog/fast-javascript-maxmin/

Comments

0

Don't pass it an array (which is what is not a number or NaN in this case), just pass it the numbers as arguments to the function. Like this:

Math.min(1, 2, 3)

2 Comments

@compile then use something like vbence suggests.
@compile-fan: Why do you have to? The function is expecting numbers as arguments, not an array. If you have to pass an array to a function then I suppose you could write a wrapper for Math.min() which takes an array and breaks it up before calling Math.min() with the array's elements. (And even checks the input to make sure they're all numbers.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.