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?
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?
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
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.
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.