Reputation: 91
I'm not getting the minimum value and it shows 0 but in this case of Math.max(), it shows the right maximum value. Why is it so?
function values(ar) {
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]);
Upvotes: 1
Views: 1038
Reputation: 5234
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]))
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));
Upvotes: 0
Reputation: 1356
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)
Upvotes: 2
Reputation: 6081
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.
Upvotes: 0