Home > OS >  I am not getting the minimum value ,it showing 0, but in case of Math.max() it showing the right max
I am not getting the minimum value ,it showing 0, but in case of Math.max() it showing the right max

Time:10-24

I am not getting the minimum value ,it showing 0, but in case of Math.max() it showing the right maximum value, why is it so?

    var min_val = 0;
    for(var i = 0; i < ar.length; i  ) {
         min_val = Math.min(min_val,ar[i]);
            }
document.write(min_val);
}
values([14,99, 10, 18,19, 11, 34]);```

CodePudding user response:

For your expected behavior, in order to find the minimum, you want to start at the absolute maximum (Infinity).

    var min_val = Infinity;
    for(var i = 0; i < ar.length; i  ) {
         min_val = Math.min(min_val,ar[i]);
            }
document.write(min_val);
}
values([14,99, 10, 18,19, 11, 34]);```

This will write Infinity for empty arrays, or the minimum value for the input.

CodePudding user response:

It always returns 0 because you compare it to min_val. Where min_val becomes the lowest value as 0 is lower then any value in the array. Therefor min_val will always be set equal to itself and stay 0. Here is my fix :

let ar =[14,99,10,18,19,11,34]
let min_val = Math.min(...ar)
console.log(min_val)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe> This is also more elegant than a for-loop.

CodePudding user response:

Math.min() receivec arguments like Math.min(-2, -3, -1) or with array Math.min(...arr). You are giving these arguments Math.min([14,99, 10, 18,19, 11, 34], 0) where 0 is minimum. So you are receiving 0. Also, no need for a loop as Math.min() finds the minimum. So, the solution would be:

    function values(ar) {
        var min_val = Math.min(...ar);
        //document.write(min_val);
        return min_val
    }
    console.log(values([14,99, 10, 18,19, 11, 34]))
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

or (to match your case)

function values(ar) {
    var min_val = Math.min(...ar);
    
    document.write(min_val);
}

in shortest form:

document.write(Math.min(...ar));
  • Related