Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to use Math.min to get second smallest number from array?

Tags:

javascript

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);
like image 590
user13286 Avatar asked Nov 15 '17 20:11

user13286


1 Answers

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);
like image 109
skyboyer Avatar answered Nov 26 '22 07:11

skyboyer