-1

I'm using Math.min() to find the lowest price, but the variables passed might have 0 sometimes if the product is unavailable:

Math.min( 101.06, 99.99, 0 );

.. in this case, the result is 0. How do I filter it out?

Cœur
  • 37,241
  • 25
  • 195
  • 267
eozzy
  • 66,048
  • 104
  • 272
  • 428
  • 2
    How is the variable passing zero? Can we see some more code, please? – 9Deuce Mar 26 '15 at 21:02
  • You can use [this](http://stackoverflow.com/questions/5817756/delete-zero-values-from-array-with-javascript) to remove all values of 0 and just run `Math.min` on the filtered data – Bijan Mar 26 '15 at 21:03
  • 1
    `Math.min.apply(null, [101.06, 99.99, 0].filter(Number))==99.99` – dandavis Mar 26 '15 at 21:04

3 Answers3

3

I'm guessing you want the smallest positive number:

function positiveMin(arr) {
  var min;
  arr.forEach(function(x) {
    if (x <= 0) return;
    if (!min || (x < min)) min = x;
  });
  return min;
}

positiveMin([101.06, 99.99, 0, -1]); // => 99.99
positiveMin([0]); // => undefined
maerics
  • 151,642
  • 46
  • 269
  • 291
  • a solution based on reduce() would be faster than forEach()+closure in this case, but the code would be much the same. – dandavis Mar 26 '15 at 21:25
3

You can use .apply to pass arguments as an array,

fun.apply(thisArg, [argsArray])

- https://developer.mozilla.org/

This means that you can filter your arguments, checking for any properties you would like.

So, in your case just do:

Math.min.apply(this, [101.06, 99.99, 0].filter(Number) );

This method has other benefits as well, it seems like you would be dynamically generating your arguments, and it would be easier to pass a generated array than actual arguments.

theonlygusti
  • 11,032
  • 11
  • 64
  • 119
0

Here's a simple function:

Math.positiveMin = function(){
  arguments = Array.prototype.slice.call(arguments);
  return arguments.reduce(function(min, current){
    return (current > 0 && current < min) ? current : min;
  }, arguments[0]);
};

returns zero if there are no arguments greater than 0.

Possible benefit of this method over my previous: you were passing arguments individually in your example, and you can do that with this method:

Math.positiveMin( 101.06, 99.99, 0 );

will work just as you expect, no need for an array.

theonlygusti
  • 11,032
  • 11
  • 64
  • 119