JavaScript - Find Second Largest Element in an Array
Here are the different approaches to find the second largest element in an arary using JavaScript.
1. Using Sorting
Sort the array in ascending order. Iterate from the end of the sorted array to find the first element that is different from the largest. If no such element is found, return null, indicating there is no second-largest element.
let a = [10, 20, 4, 45, 99, 99];
a.sort((a, b) => b - a);
let first = a[0];
let res = null;
for (let i = 1; i < a.length; i++) {
if (a[i] < first) {
res = a[i];
break;
}
}
console.log(res !== null ? res : "No second largest element");
Output
45
In this example
- The array is sorted in descending order.
- The first element (a[0]) is the largest.
- The loop finds the first element smaller than a[0] to ensure the second largest is distinct.
- If all elements are the same, it prints "No second largest element".
2. Using Set
A Set is a built-in JavaScript object that stores unique values. By converting the array into a Set, you can automatically remove duplicates, making it easier to find the second-largest element.
let a = [10, 20, 4, 45, 99, 99, 45];
let uni = [...new Set(a)];
uni.sort((a, b) => b - a);
let res = uni[1];
console.log(res);
Output
45
In this example
- A Set is used to remove duplicates from the array.
- The unique elements are sorted in descending order.
- The second largest element is at index 1 after sorting.
3. Using Iteration
To find the second largest element using iteration, initialize two variables, largest and secondLargest, to -Infinity. Loop through the array, and if an element is larger than largest, update secondLargest to largest and largest to the element.
let a = [10, 20, 4, 99, 99, 45];
let b = -Infinity,
c = -Infinity;
for (let num of a) {
if (num > b) {
c = b;
b = num;
} else if (num > c && num < b) {
c = num;
}
}
console.log(c);
Output
45
In this example
first
is initialized to-Infinity
to track the largest number, andsecond
is initialized to-Infinity
for the second largest.- As we iterate through the array, we update
first
andsecond
based on comparisons. - After the loop,
second
holds the second largest element.
4. Using Two Variables
Using two variables, track the largest and second largest elements while iterating through the array, updating them as necessary to find the second largest value.
let a = [1, 2, 3, 4, 5, 5];
let [fir, sec] = [-Infinity, -Infinity];
for (let n of a) {
if (n > fir) {
[sec, fir] = [fir, n];
} else if (n > sec && n < fir) {
sec = n;
}
}
console.log("The sec largest element is: " + sec);
Output
The sec largest element is: 4
In this example
- first and second: Track the largest and second-largest elements.
- The for...of loop updates first and second by comparing each element.
- The second largest element is printed directly.
5. Using Array.slice and Array.sort
Using Array.slice creates a copy of the array, which is then sorted using Array.sort.
const a = [10, 5, 20, 8, 20, 15];
const sort = a.slice().sort((a, b) => b - a);
let sec = null;
for (let i = 1; i < sort.length; i++) {
if (sort[i] < sort[0]) {
sec = sort[i];
break;
}
}
console.log("Second largest element:", sec !== null ? sec : "No second largest element");
Output
Second largest element: 15
In this example
- We first sort the array in descending order.
- Then, we loop through the sorted array starting from the second element and find the first element that is smaller than the largest element (sort[0]).
- If no such element exists (all elements are the same), the message "No second largest element" is printed.
6. Using Reduce Method
The reduce() method is used to find the largest and second largest elements in a single pass through the array.
let a = [10, 20, 4, 99, 99, 45];
let res = a.reduce(
(acc, num) => {
if (num > acc[0]) {
acc[1] = acc[0];
acc[0] = num;
} else if (num > acc[1] && num < acc[0]) {
acc[1] = num;
}
return acc;
},
[-Infinity, -Infinity]
);
console.log(res[1]);
Output
45
In this example
- The reduce method is used to iterate through the array while maintaining two values: acc[0] for the largest and acc[1] for the second largest.
- During each iteration, the values are updated based on comparisons.
- After the reduction, acc[1] holds the second largest element.