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.
Simplest Case: a sorted array
If you know the array is already sorted, getting the second largest number is simple:
const arr = [1, 2, 3];function findSecondLargest(arr) {
return arr[arr.length - 2];
}
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!
const arr = [1, 3, 2];function findSecondLargest(arr) {
const arrSorted = arr.sort((a, b) => a - b);
return arrSorted[arr.length - 2];
}
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:
function findSecondLargest(arr) {
const distinct = [...new Set(arr)];
const distinctSorted = distinct.sort((a, b) => a - b);
return distinctSorted[distinctSorted.length - 2];
}
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:
function findSecondLargest(arr) {
const distinct = [...new Set(arr)];
const maxNum = Math.max(...distinct);
const filteredMaxOut = distinct.filter((num) => num < maxNum);
const secondMax = Math.max(...filteredMaxOut);
return secondMax;
}
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.