Emmanuel Akinfulubi

JavaScriptFunction

Second smallest and second largest number in JavaScript

Intermediate · 4 min read

Finding the second smallest and second largest number in a list sounds like a small twist on finding the minimum and maximum. For [1, 2, 3, 4, 5] the answers are 2 and 4. Leaderboards ("who came second?"), price lists ("the second cheapest option") and exam results all ask this question.

In this tutorial you will write secondValues, a function that returns both numbers in one object. On the way you will meet two classic sort traps, decide what duplicates should mean, and finish with a faster one-pass version. You need to know what an array and an object are.

The plan

If the numbers are sorted from smallest to largest, the second smallest is at index 1 and the second largest is the one before the last. So the plan is:

  1. Sort the numbers.
  2. Read the second item from each end.
  3. Handle lists that don't have a second value at all.

Reading from the end with at()

array.at(index) reads an item like array[index] does, but it also accepts negative numbers, which count from the end. at(-1) is the last item and at(-2) is the one before it:

JavaScript

const sorted = [1, 2, 3, 4, 5];
console.log(sorted[1]);    // 2
console.log(sorted.at(-2)); // 4

Here is the exercise. Try it yourself first if you like, or read on and we will build it together.

11 Second lowest and second greatest

fair

[1,2,3,4,5] should give 2 and 4. Decide what duplicates mean, and what happens when there is no second value.

Stuck? Three hints, smallest first
  1. 1. Sorting is the simple route, but sort() mutates and compares as text by default.
  2. 2. Duplicates are the real question: in [1,1,2], is the second lowest 1 or 2?
  3. 3. A list with fewer than two distinct values has no answer. Say so rather than returning undefined.

Step 1: sort numbers the right way

The first trap: sort() with nothing in the brackets compares items as text. As text, '100' comes before '9', because '1' comes before '9':

Step 1

console.log([10, 9, 100].slice().sort()); // [ 10, 100, 9 ]
console.log([10, 9, 100].slice().sort((a, b) => a - b)); // [ 9, 10, 100 ]

The fix is a compare function. sort calls it with two numbers, a and b. A negative result puts a first, a positive one puts b first. a - b is negative exactly when a is smaller, so the list comes out smallest first.

Step 2: don't change the caller's array

The second trap: sort mutates, which means it rearranges the original array in place. Whoever passed you the list would find it reordered. Copy first with the spread syntax [...numbers]:

Step 2

const original = [3, 1, 2];
const copy = [...original].sort((a, b) => a - b);
console.log(copy);     // [ 1, 2, 3 ]
console.log(original); // [ 3, 1, 2 ]

Step 3: decide what duplicates mean

Now the real question. In [1, 1, 2, 2, 3], what is the second smallest? By position in the sorted list it is 1, because there are two of them. By value, the second different number is 2. The example in the exercise has no repeats, so it can't tell you. Most people asking "second lowest" mean the second different value.

A Set keeps only one copy of each value. Spreading it back into an array gives you the distinct values:

Step 3

console.log([...new Set([1, 1, 2, 2, 3])]); // [ 1, 2, 3 ]

Step 4: put it together

Step 4

function secondValues(numbers) {
  const distinct = [...new Set(numbers)].sort((a, b) => a - b);
  if (distinct.length < 2) return null;
  return { secondLowest: distinct[1], secondGreatest: distinct.at(-2) };
}
console.log(secondValues([1, 2, 3, 4, 5]));  // { secondLowest: 2, secondGreatest: 4 }
console.log(secondValues([1, 1, 2, 2, 3])); // { secondLowest: 2, secondGreatest: 2 }
console.log(secondValues([5, 5, 5]));        // null

Spreading the Set already makes a new array, so the caller's list is safe. A list with fewer than two different values has no "second" at all. Returning null says that clearly. Without the check you would get undefined back, which is easy to miss.

For comparison, the answer also has secondByPosition, which sorts a copy without removing duplicates. For [1, 1, 2, 2, 3] it gives a second lowest of 1. Both are reasonable; what matters is choosing one and testing it.

Step 5: one pass, no sorting

Sorting does more work than you need. You can find the second smallest in one walk through the list by remembering two numbers: the lowest so far and the second lowest so far. Both start at Infinity, which is bigger than any number:

Step 5

function secondLowestOnePass(numbers) {
  let lowest = Infinity;
  let second = Infinity;
  for (const n of numbers) {
    if (n < lowest) { second = lowest; lowest = n; }
    else if (n > lowest && n < second) second = n;
  }
  return second === Infinity ? null : second;
}
console.log(secondLowestOnePass([5, 1, 9, 1])); // 5
console.log(secondLowestOnePass([7]));          // null

When a new lowest number arrives, the old lowest moves down to second place. The n > lowest part skips duplicates of the lowest, so 1 can't be both first and second. If second is still Infinity at the end, there was no second value.

The full solution

The panel has secondValues, secondByPosition and secondLowestOnePass. It prints the example, the duplicates case both ways, lists with one or all-identical values, and the text-sorting trap. Press Run to see the output.

The answer

// Distinct values, which is almost always what "second lowest" means.
function secondValues(numbers) {
  const distinct = [...new Set(numbers)].sort((a, b) => a - b);   // copy, numeric compare
  if (distinct.length < 2) return null;
  return { secondLowest: distinct[1], secondGreatest: distinct.at(-2) };
}

// By position instead, counting duplicates as separate entries.
function secondByPosition(numbers) {
  if (numbers.length < 2) return null;
  const sorted = [...numbers].sort((a, b) => a - b);
  return { secondLowest: sorted[1], secondGreatest: sorted.at(-2) };
}

// One pass, no sorting. O(n) rather than O(n log n).
function secondLowestOnePass(numbers) {
  let lowest = Infinity;
  let second = Infinity;
  for (const n of numbers) {
    if (n < lowest) { second = lowest; lowest = n; }
    else if (n > lowest && n < second) second = n;
  }
  return second === Infinity ? null : second;
}

const sample = [1, 2, 3, 4, 5];
console.log("the sample:", secondValues(sample));
console.log('with duplicates [1,1,2,2,3]:');
console.log('  distinct :', secondValues([1, 1, 2, 2, 3]));
console.log('  by position:', secondByPosition([1, 1, 2, 2, 3]), '<- second lowest is 1');
console.log('all the same [5,5,5]:', secondValues([5, 5, 5]));
console.log('one element        :', secondValues([1]));
console.log('sort() as text would give:', [10, 9, 100].slice().sort());

Output


      
16 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 16 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

16 checks

test("the example in the question", secondValues(sample), { secondLowest: 2, secondGreatest: 4 });
test('two elements', secondValues([1, 2]), { secondLowest: 2, secondGreatest: 1 });
test('negatives sort correctly', secondValues([-5, -1, 0, 3]), { secondLowest: -1, secondGreatest: 0 });
test('a numeric comparator is needed', secondValues([10, 9, 100, 1]), { secondLowest: 9, secondGreatest: 10 });
test('without one, sort compares as text', [10, 9, 100].slice().sort(), [10, 100, 9]);
test('duplicates are collapsed by default', secondValues([1, 1, 2, 2, 3]), { secondLowest: 2, secondGreatest: 2 });
test('while by position they are not', secondByPosition([1, 1, 2, 2, 3]).secondLowest, 1);
test('so the two answers differ', secondValues([1, 1, 2, 2, 3]).secondLowest === secondByPosition([1, 1, 2, 2, 3]).secondLowest, false);
test('all-identical values have no second', secondValues([5, 5, 5]), null);
test('one element has no second', secondValues([1]), null);
test('an empty list has no second', secondValues([]), null);
test('the input is not modified', (() => { const a = [3, 1, 2]; secondValues(a); return a; })(), [3, 1, 2]);
test('the one-pass version agrees on the second lowest', secondLowestOnePass(sample), 2);
test('and on a list with duplicates', secondLowestOnePass([1, 1, 2]), 2);
test('and reports null when there is none', secondLowestOnePass([5, 5]), null);
test('it agrees with the sorting version generally', [[1, 2, 3], [5, 1, 9, 1], [-2, 0], [7]].every((a) => secondLowestOnePass(a) === (secondValues(a)?.secondLowest ?? null)), true);

The specification gap is duplicates. In [1, 1, 2], "second lowest" is either 1 (the second element in sorted order) or 2 (the second distinct value), and the example in the question cannot tell you which because it has none. Both are implemented and the assertion showing them disagree is the honest answer — pick one and pin it down with a test.

Two mechanical points. [...numbers].sort(...) copies first, because sort mutates; and it needs the (a, b) => a - b comparator, because the default converts to text and puts 100 before 9. Both are asserted.

secondLowestOnePass is worth the extra lines when the list is large: one pass instead of a sort. The n > lowest condition in the else-if is what makes it skip duplicates rather than counting them.

Common mistakes

  • Calling sort() without a compare function. Numbers are sorted as text, so 100 lands before 9.
  • Sorting the caller's array. sort changes the original. Copy it first with [...numbers].
  • Ignoring short lists. [5] or [5, 5] has no second value. Return null on purpose instead of an accidental undefined.

Try it yourself

  1. Write secondGreatestOnePass(numbers) by flipping the comparisons in Step 5.
  2. Change secondValues so it returns the third lowest and third greatest. What should the length check become?
  3. Run secondValues([-5, -1, 0, 3]) and explain why the second greatest is 0.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.