Emmanuel Akinfulubi

JavaScriptBasic

Find the second largest number in an array in JavaScript

Intermediate · 4 min read

Finding the second largest number in a list is a favorite interview question. It is also a real task: the runner-up in a competition, the second-highest bid, the next-best price. It looks easy (sort the list and take the second item), and that easy answer is wrong as soon as the top value appears twice.

In this tutorial you will write secondLargest(values), which returns the second largest distinct value, or undefined when there isn't one. Then you will write secondLargestOnePass, which gets the same answer in a single walk through the list, with no sorting at all. You need to know what an array, a loop and a function are.

Sorting numbers in JavaScript

sort() with nothing in the brackets sorts values as text, which puts numbers in a strange order:

JavaScript

console.log([10, 5, 8].sort()); // [ 10, 5, 8 ]: '1' comes before '5' as text

To sort numbers, pass a compare function. sort calls it with two values, a and b. A negative result puts a first, a positive result puts b first. So (a, b) => b - a sorts from biggest to smallest:

JavaScript

console.log([10, 5, 8].sort((a, b) => b - a)); // [ 10, 8, 5 ]

Remember that sort rearranges the array it is called on. Spreading into a copy first, [...values], keeps the original safe.

Two meanings of "second"

Take [10, 5, 8, 10, 3]. After sorting from biggest to smallest it is [10, 10, 8, 5, 3]. The second item is 10. The second value, ignoring repeats, is 8. The question doesn't say which it wants. This tutorial picks 8, the second distinct value, because "the second largest number is the largest number" is rarely what anyone means.

Here is the exercise. Try it yourself first if you like, or follow the steps.

28 Find the second largest value

fair

Find the second largest number in a list. Decide what counts as second when the largest value appears more than once.

Stuck? Three hints, smallest first
  1. 1. Sorting descending and taking index 1 gives the second element, not the second distinct value.
  2. 2. For distinct values, dedupe first with a Set.
  3. 3. A single pass tracking the best two is possible and does not need sorting at all.

Step 1: the naive version

Sort a copy from biggest to smallest and take position 1:

JavaScript

const naive = [...[10, 5, 8, 10, 3]].sort((a, b) => b - a)[1];
console.log(naive); // 10

It gives back 10, the largest value again, because 10 appears twice.

Step 2: remove the repeats first

A Set keeps each value only once. Spread it back into an array, then sort:

JavaScript

console.log([...new Set([10, 5, 8, 10, 3])]);                       // [ 10, 5, 8, 3 ]
console.log([...new Set([10, 5, 8, 10, 3])].sort((a, b) => b - a)); // [ 10, 8, 5, 3 ]

Now position 1 holds 8.

Step 3: handle lists with no second value

[4] has only one value. [4, 4, 4] has three items but only one distinct value. Neither has a second largest. Returning a made-up number here would be worse than returning nothing, so return undefined:

Step 3

function secondLargest(values) {
  const distinct = [...new Set(values)].sort((a, b) => b - a);
  if (distinct.length < 2) return undefined;
  return distinct[1];
}
console.log(secondLargest([10, 5, 8, 10, 3])); // 8
console.log(secondLargest([4, 4, 4]));         // undefined
console.log(secondLargest([4]));               // undefined
console.log(secondLargest([-1, -5, -3]));      // -3

Negative numbers need no special care: the compare function handles them.

Step 4: one pass, no sorting

Sorting puts the whole list in order, which is more work than we need. We only care about the top two. So walk through the list once and keep two variables: best (the largest so far) and second (the runner-up so far).

Both start at -Infinity, a special number smaller than every other number, so the first real values always beat them. For each number n there are three cases:

  • n is bigger than best: the old best becomes the runner-up, and n becomes the new best.
  • n is smaller than best but bigger than second: n is the new runner-up.
  • Anything else (including n equal to best): ignore it.

Step 4

function secondLargestOnePass(values) {
  let best = -Infinity;
  let second = -Infinity;
  for (const n of values) {
    if (n > best) {
      second = best;
      best = n;
    } else if (n < best && n > second) {
      second = n;
    }
  }
  return second === -Infinity ? undefined : second;
}
console.log(secondLargestOnePass([10, 5, 8, 10, 3])); // 8
console.log(secondLargestOnePass([4, 4, 4]));         // undefined

Trace [10, 5, 8, 10, 3]: 10 becomes best. 5 becomes second. 8 beats 5, so second is 8. The next 10 equals best, so it is ignored. 3 is too small. The answer is 8.

The n < best check is what skips repeats of the top value. Without it, the second 10 would become the runner-up. If second is still -Infinity at the end, no runner-up was ever found, so we return undefined.

The full solution

The complete answer has both versions, shows the naive sort returning the duplicate 10, and checks the cases with no second value. Press Run to see the output.

The answer

// Second distinct value.
function secondLargest(values) {
  const distinct = [...new Set(values)].sort((a, b) => b - a);
  if (distinct.length < 2) return undefined;
  return distinct[1];
}

// One pass, no sorting, no extra array.
function secondLargestOnePass(values) {
  let best = -Infinity;
  let second = -Infinity;
  for (const n of values) {
    if (n > best) {
      second = best;
      best = n;
    } else if (n < best && n > second) {
      second = n;
    }
  }
  return second === -Infinity ? undefined : second;
}

console.log(secondLargest([10, 5, 8, 10, 3]));
console.log('one pass agrees:', secondLargestOnePass([10, 5, 8, 10, 3]));

// The trap: sorting without deduping gives 10 again.
const naive = [...[10, 5, 8, 10, 3]].sort((a, b) => b - a)[1];
console.log('without deduping:', naive);

Output


      
7 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 7 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

7 checks

test('second distinct value', secondLargest([10, 5, 8, 10, 3]), 8);
test('the naive version returns the duplicate', naive, 10);
test('one pass agrees', secondLargestOnePass([10, 5, 8, 10, 3]), 8);
test('all values identical has no second', secondLargest([4, 4, 4]), undefined);
test('a single value has no second', secondLargest([4]), undefined);
test('negatives work', secondLargest([-1, -5, -3]), -3);
test('both methods agree on a plain list', secondLargestOnePass([1, 2, 3]), secondLargest([1, 2, 3]));

The ambiguity is the exercise. In [10, 5, 8, 10, 3] the second element after sorting is 10, but the second distinct value is 8, and the question does not say which it wants. Deciding that explicitly, and returning undefined rather than a wrong number when there is no answer, is most of the work.

Common mistakes

  • Sorting without deduping. When the top value repeats, position 1 is the top value again.
  • Calling sort() with no compare function. It sorts as text, so [10, 5, 8] stays [10, 5, 8].
  • Starting the one-pass trackers at 0. In a list of negative numbers like [-1, -5, -3], nothing beats 0, and you get a wrong answer. Start at -Infinity.

Try it yourself

  1. Write secondSmallest(values) by changing the sort order.
  2. Change secondLargest into nthLargest(values, n), so nthLargest([10, 5, 8], 3) is 5.
  3. Make the one-pass version also return the largest value: { best: 10, second: 8 }.

Keep practising

Newsletter

New writing, when it lands.

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