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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read