0

I have an array of 3 numbers. I would like to get the smallest and the second smallest numbers from this array provided the number is not 0.

Let's say my array is as follows:

[459, 25, 0]

In this case I would like 25 reported as smallest and 459 reported as second smallest. I am able to get 25 as the smallest like this:

var arr = [459, 25, 0];
var smallest = Math.min.apply(null, arr.filter(Boolean));

console.log(smallest);

But how would I go about getting the second smallest number that isn't 0? Here is what I tried, but this returns 0.

var arr = [459, 25, 0];
var smallest = Math.min.apply(null, arr.filter(Boolean));
var secSmallest = Math.min.apply(null, arr.filter(n => n != smallest));

console.log(secSmallest);
user13286
  • 3,027
  • 9
  • 45
  • 100

6 Answers6

3

User filter and sort

var arr = [459, 25, 0];
const [smallest, next_smallest] = arr.filter(x => x).sort((a, b) => a - b);

console.log(smallest, next_smallest);
Siva K V
  • 10,561
  • 2
  • 16
  • 29
2

You could get the smallest and filter the smallest and get the second smallest value.

var array = [459, 25, 0],
    smallest = Math.min(...array.filter(Boolean)),
    secondSmallest = Math.min(...array.filter(v => v && v !== smallest));

console.log(smallest);
console.log(secondSmallest);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 1
    This is problematic if you have `[100, 7, 7]` as the two smallest numbers are actually `7` and `7`, not `100` and `7` – VLAZ Feb 07 '20 at 18:05
1

found an answer to this question here. Below is the code

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);
Gangula
  • 5,193
  • 4
  • 30
  • 59
  • This is the only answer so far that avoids scanning the array twice or even sorting it. But you need to add an additional check to exclude the 0 from consideration. – Heiko Theißen Aug 19 '23 at 09:17
0

One way is to use splice, and splice the first number out and then call Math.min on the new spliced array.

array.splice(indexOfItem, 1);
Derek Lawrence
  • 1,551
  • 2
  • 16
  • 36
0

What about that?

let arr = [3,5,10,1,30];
let smallest = Math.min(...arr.filter(n => n != 0));
let second_smallest = Math.min(...arr.filter(n => n != 0 && n > smallest));
console.log(smallest);
console.log(second_smallest);
nickland200
  • 47
  • 10
0

const getNthSmallest = (nth, arr) => arr.slice().sort()[nth - 1]

console.log(getNthSmallest(2, [0, 1, 2, 3].filter(Boolean)))
Đinh Carabus
  • 3,403
  • 4
  • 22
  • 44