Pop quiz: How do you find the second largest number in an array in JavaScript?

I was recently solving a problem, where one of the sub problems to solve was finding the second largest number in an array of integers. I’m humble enough to admit it: I froze for a bit. I know the typical methods for moving/returning at the start and end we use all the time (pop, shift, unshift, etc). But what about the element that’s 2nd to last?

Let’s walk through a few scenarios with increasing complexity.

We want #2!

Simplest Case: a sorted array

If you know the array is already sorted, getting the second largest number is simple:

This will return the element that is at the position of the length of the array, minus 2. That’s 2, the second largest number.

Slightly more complex: unsorted array

What if we don’t know if our array is sorted? Just one extra step: sort it!

This will first sort your array, and then apply the same process as before: return the element that is at the position of the length of the array, minus 2, also 2.

Most Complex: a jumbled up array

What if not only we can’t assume our array is sorted, but it also has duplicates?

First, we assume we want to remove the duplicates, so that if the array was const arr = [3, 1, 1, 2, 3, 2], we’d still want to return 2. Here’s the algorithm:

  • Make a new array, with duplicates removed
  • Sort it.
  • Return second to last one

Here’s the code:

Bonus: doing it without manually sorting

If we’re feeling fancy, we could’ve the task outlined before with another method:

  • Make a new array, with duplicates removed
  • Get the largest number, and filter out that number from the array with duplicates removed
  • Return the new largest number

Here’s the code for that:

Not necessarily better, considering more memory usage and similar time complexity, but it’s good to know a few ways to solve this problem.

And remember…

Grit > talent.

Always learning.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store