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);
Best Answer
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 removingmin
from the array.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: