I am using Math.min
to get the smallest number out of an array of numbers. However, I also need to get the second smallest number as well. Wondering if there is a way to do this using Math.min
as well, otherwise looking for the best way to get this number.
Here's what I have:
var arr = [15, 37, 9, 21, 55];
var min = Math.min.apply(null, arr.filter(Boolean));
var secondMin; // Get second smallest number from array here
console.log('Smallest number: ' + min);
console.log('Second smallest number: ' + secondMin);
just to make that thread completed: the fastest way is to iterate all the elements just like you can do to find minimum. But up to your needs there will be two variables used: first minimum (candidate) and second one.
This logic is O(N) while sorting approach is O(N lg(N)).
But maybe you shouldn't care if this is just for practice.
In case repeatition should be processed as independant value(just like it would be for .sort(...)[1]
) then it should <=
be used instead of <
.
var arr = [15, 37, 9, 21, 55];
var min = Infinity, secondMin = Infinity;
for (var i= 0; i< arr.length; i++) {
if (arr[i]< min) {
secondMin = min;
min = arr[i];
} else if (arr[i]< secondMin) {
secondMin = arr[i];
}
}
console.log('Smallest number: ' + min);
console.log('Second smallest number: ' + secondMin);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With