Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

1. ## Smallest Positive Number

I know to get the smallest number is quite simple,`Math.min(-6,5,12)`, and you would get -6.

But from that example how would you go about getting 5?

2. Originally Posted by Md8^h2nx
I know to get the smallest number is quite simple,`Math.min(-6,5,12)`, and you would get -6.

But from that example how would you go about getting 5?
One way would be to use apply to pass the parameters as a filtered array:

```alert( Math.min.apply( null, [-6,5,12].filter( function( e ){ return e > 0; } ) ) ); ```

3. ## Users who have thanked Logic Ali for this post:

Md8^h2nx (06-05-2013)

4. Simpler but still effective:-

Code:
```<script type = "text/javascript">

var myarray = [-6, 5,12, 3,-34];
var min = 1e20;  // a big number
for (var i=0; i<myarray.length;i++) {
if ((myarray[i] >= 0) && (myarray[i] < min)) {
min = myarray[i];
}
}
alert ("The lowest positive value in the array is " + min);

</script>```
Quizmaster: "Far From The Madding Crowd" is a novel by which author?
Contestant: Ian Fleming

5. Yeah, but how do you do it WITHOUT using an array?

Only way I see would be to write a simple function:
Code:
```function minAbs( )
{
var args = Array.prototype.slice.call(arguments);
args = args.filter( function(e) { return e > 0; } );
return Math.min.apply( null, args );
}
alert( minAbs( -6, 5, 12 ) );```
And of course the 3 lines in that function can be reduced to one line, but I prefer to leave it like that for the sake of clarity.

Of course, if you want it to run in all browsers--including old MSIE that doesn't have filter--you could just do it the dirt simple way:
Code:
```function minAbs( )
{
var min = null;
for ( var a = 0; a < arguments.length; ++a )
{
var n = arguments[a];
if ( n > 0 && ( min === null || n < min ) ) min = n;
}
return min;
}

alert( minAbs( -6, 5, 12 ) );```
And I wouldn't be at all suprised to find that's at least as fast as using filter and apply and slice and call in the much harder to understand version.

N.B.: If you want to find zero as a possible minimum, change n > 0 to n >= 0 (same applies to the filter version where you would use e >= 0).

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•