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

I see you are using Array.filter (but why?) on your first min. So, if we are using ES6 features you can find the second lowest value by first removing min from the array.

var secondMin = Math.min.apply(null, arr.filter(n => n != min));

edit: for clarity, unless you are doing something very clever with Array.filter(Boolean) while calculating the first min, you should just pass it the array without filtering:

var min = Math.min.apply(null, arr);

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);


@skyboyer provides what is probably the fastest algorithm for finding the two smallest elements. Another type algorithm that runs in O(n) time is selection (in the general comp-sci definition, not how it is normally used in JavaScript), which will find the kth smallest element of an array and separate the elements into those larger and those smaller than the kth.

Even though most partitioning selection algorithms (quickselect, Floyd-Rivest, introselect) run in O(n) time, @skyboyer's answer will be faster because of the specific nature of the partition you are looking for, and because all those algorithms come with a heavy constant factor.

There is a javascript library implementing Floyd-Rivest, but named quickselect that can do the partitioning for you, in place:

quickselect(arr, 1)

arr will be rearranged so that arr[0] is the minimum, arr[1] is the second smallest element, and the remaining elements are in some arbitrary order.

Tags:

Javascript