Minimum number without zero

I need to find the minimum number from a list of numbers excluding zero (s).

Is there some kind of internal function that will do this? Or do I need to remove zero from the list before use Math.min?

Example:

Input: 213, 0, 32, 92, 0, 2992,39

Result: 32


[UPDATE] If possible, specify the code for a function that will take input as arguments, for examplenonZeroMin(213, 0, 32, 92, 0, 2992, 39)

+5
source share
6 answers

Code / Solution:

var arr = [3, 0, 7, 12, 0, 5, 22];
var minValue = Math.min.apply(null, arr.filter(Boolean));

How it works:

arr.filtercreates a new array with all the elements that pass the test implemented by the provided function. Thus, in the code above, each value of the array will be checked forBoolean(value)

Boolean(3) // true 
Boolean(0) // false
Boolean(7) // true
// ...

, , .

Math.min.apply(null, ...) min .

null . null, this, Math - .

+5
var arr = [213, 0, 32, 92, 0, 2992, 39];

var min = arr.filter(function (x) { return x !== 0; })
    .reduce(function (a, b) { return Math.min(a, b); }, Infinity); 

alert(min);  // => 32

filter reduce EcmaScript 5 Array, MDN code .


EDIT: , var-args.

 function minNonZero(var_args) {
   return Array.prototype.reduce.call(arguments, function (prev, current) {
     return prev && current ? Math.min(prev, current) : prev || current;
   });
 }

 alert(minNonZero(213, 0, 32, 92, 0, 2992, 39));
+8

, , :

list.filter(function(x){ 
    return x> 0;
}).sort(function(a,b){
   return a>b;
})[0];
+5

?

var arry = [213, 0, 32, 92, 0, 2992, 39];
Math.min.apply(Math, arry.filter(Number)); // => 32
+4

, Math.min, :

function nonZeroMin() { // input can be as many parameters as you want
    var args = Array.prototype.slice.call(arguments);
    for(var i = args.length-1; i>=0; i--) {
        if(args[i] == 0) args.splice(i, 1);
    }

    return Math.min.apply(null,args);
}

Edited to allow input parameters in accordance with the updated question.

+3
source

If you want to create a function that takes an unknown number of arguments, you can use argumentsinside this function.

To find the lowest nonzero number, you can sort the array and sort zeros (and not numbers) to the end.

function nonZeroMin(){
    var args = Array.prototype.slice.call(arguments);
    args.sort(function(a, b){
        if(a === null || isNaN(a) || a === 0) return 1;
        if(b === null || isNaN(b) || b === 0) return -1
        return a-b;
    });
    return args[0];
}

Then you can do: nonZeroMin(213, 0, 32, 92, 0, 2992, 39).

+3
source

All Articles