Profile Picture

Prajwal Dhungana

Go Back

How To Find The Second Largest Unique Number in a JavaScript Array

Published on Jul 09, 2025

This is one of those questions that shows up all the time in interviews:

“Given an array of unsorted numbers, return the second largest unique number.”

Let’s go over two practical ways to solve it:

  1. A straightforward method using sort
  2. A more efficient single-pass solution

Both will handle edge cases like arrays with fewer than two unique numbers or all values being the same.


Example

const arr = [10, 5, 20, 8, 20];

Here, the largest number is 20. The second largest unique number is 10. We don't want 20 again — only distinct values count.


Option 1: Using Sort + Set

This approach removes duplicates and sorts the array in descending order. It's easy to read and works fine for most situations.

JavaScript Playground
Loading...
Console

Notes:

  • Time complexity: O(n log n) due to sorting
  • Simple and readable
  • Not the most efficient for large arrays

Option 2: Single-Pass (More Efficient)

This version avoids sorting altogether. It just loops through the array once and keeps track of the top two unique values.

JavaScript Playground
Loading...
Console

Notes:

  • Time complexity: O(n)
  • Uses constant space (excluding the set)
  • Better suited for performance-critical cases

Summary

Both methods get the job done. If performance isn't a concern and you want something quick and readable, go with the sort-based version. If you're optimizing for efficiency or large datasets, the single-pass version is the better choice.

Hash Tags:

#Javascript
#Sorting