How to use Two Variables In Javascript
Using two variables, first and second, iterate through the array. Update first if the current element is greater, and update second if the current element is between first and second. This efficiently finds the second largest element in a single pass.
Example: In this example the function, secondLargest, finds the second largest number in an array by iterating through the elements. It keeps track of the largest and second largest values, updating them as it goes. The function then returns the second largest number.
function secondLargest(arr) {
let first = -Infinity, second = -Infinity;
for (let num of arr) {
if (num > first) {
second = first;
first = num;
} else if (num > second && num < first) {
second = num;
}
}
return second;
}
let arr = [1, 2, 3, 4, 5];
console.log("The second largest element is :" + secondLargest(arr));
Output
The second largest element is :4
Time Complexity: O(n).
Auxiliary space: O(1).
JavaScript Program to Find Second Largest Element in an Array
Finding the second largest element in an array in JavaScript involves sorting the array in descending order and then accessing the element at index 1. Alternatively, you can iterate through the array to identify the second-largest element manually.
Examples:
Input: arr[] = {12, 35, 1, 10, 34, 1}
Output: The second largest element is 34.
Explanation: The largest element of the array is 35 and the second largest element is 34
Input: arr[] = {10, 5, 10}
Output: The second largest element is 5. Explanation: The largest element of the array is 10
and the second largest element is 5
Input: arr[] = {10, 10, 10}
Output: The second largest does not exist.
Explanation: Largest element of the array is 10 there is no second largest element
There are a few approaches using which we can find the second largest element in an array:
Table of Content
- Using Sorting
- Using Set
- Using Iteration
- Using Two Variables
- Using Array.slice and Array.sort