JavaScript - Find Second Largest Element in an Array
Last Updated :
29 Jan, 2025
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.
JavaScript
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");
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.
JavaScript
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);
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.
JavaScript
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);
In this example
first
is initialized to -Infinity
to track the largest number, and second
is initialized to -Infinity
for the second largest.- As we iterate through the array, we update
first
and second
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.
JavaScript
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);
OutputThe 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.
JavaScript
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");
OutputSecond 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.
JavaScript
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]);
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.
Similar Reads
JavaScript Program to Find N Largest Elements from a Linked List This JavaScript program is designed to identify the N largest elements from a linked list. A linked list is a linear data structure where elements, known as nodes, are connected via pointers. The program iterates through the linked list to determine the N largest elements it contains. Table of Conte
4 min read
JavaScript Program to Find Top k Elements Given an array, our task is to find the top k elements in an unsorted array of integers in JavaScript, either the largest or the smallest. Duplicate values may be in the array. The output will be a new array with the top k elements arranged in a non-ascending order (from largest to smallest). Table
4 min read
JavaScript Program to Find Largest Number in a Linked List Finding the largest number in a linked list is a common problem and can be efficiently solved using both iterative and recursive approaches. A linked list is a fundamental data structure where each element, known as a node, is connected to the next one, forming a chain. Table of Content Iterative Ap
3 min read
JavaScript Program to Find Largest Element in an Array In this article, we are going to learn about the largest element in an array in JavaScript. The largest element in an array refers to the value that holds the greatest numerical or lexicographic (string) order among all elements present in the array. Example: Input : [10, 15, 38, 20, 13];Output: 38H
3 min read
Find the Second Largest Element in an Array in PHP We will be given with an integer array, i.e. $array1 or $ array2, and the task is to find the second largest element in the array. There are multiple ways to approach and solve this problem however using sorting is the most common and concise approach as we use the rsort() function for further opera
3 min read
JavaScript Program to Find kth Largest/Smallest Element in an Array JavaScript allows us to find kth largest/smallest element in an array. We are given an array containing some elements, we have to find kth smallest/largest element from the array where k is a number greater than zero and less than equal to the total number of elements present in the array. There are
5 min read
JavaScript - Max Element in an Array These are the following ways to find the largest element in JS array: Note: You must add a conditional check for checking whether the given array is empty or not, if the array is not empty then you can use the given below approaches to find out the largest element among them. 1. Using the Spread Ope
4 min read
How to get n largest elements from array in JavaScript ? Here in this article, we will see how we can find the n maximum element from the array using Javascript. Example: Input: arr = [1, 2, 3, 4, 5, 6], n = 3;Output: 4, 5, 6Explanation: Here we will see the 3 largest elements in the given array are 4, 5, 6. Input: arr = [5, 76, 32, 98, 52, 57] n = 2;Outp
3 min read
C++ Program to Find the Second Largest Element in an Array In C++, an array is a data structure that is used to store multiple values of similar data types in a contiguous memory location. In this article, we will learn how to find the second largest element in an array in C++. Examples: Input: arr[] = {34, 5, 16, 14, 56, 7, 56} Output: 34 Explanation: The
3 min read
How to Find the Largest Element in an Array in PHP? Given an array containing some elements, the task is to find the largest element from an array in PHP. PHP provides several ways to achieve this, each with its own advantages and use cases. Below are the approaches to find the largest element in an array in PHP:Table of ContentUsing max() FunctionUs
4 min read