How to use Iteration In Javascript
- Initialize two variables, firstMax and secondMax, to negative infinity to ensure they are initially smaller than any possible array element.
- Iterate through the input array, arr, and compare each element with firstMax. If an element is greater than firstMax, update secondMax to firstMax and firstMax to the current element.
- Also, check that the current element is not equal to firstMax to handle cases with duplicate elements.
- If secondMax remains as negative infinity after the iteration, it means there is no distinct second largest element.
- Else, return the value of secondMax as the second largest element found in the array.
Example: In this example The function findSecondLargestUsingIteration() iterates through the array, tracking the first and second largest elements, and returns the second largest value found.
function findSecondLargestUsingIteration(arr) {
let firstMax = -Infinity;
let secondMax = -Infinity;
for (let num of arr) {
if (num > firstMax) {
secondMax = firstMax;
firstMax = num;
} else if (num > secondMax && num !== firstMax) {
secondMax = num;
}
}
if (secondMax === -Infinity) {
return "No second largest element exists";
}
return "The second largest element is " + secondMax;
}
// Example usage:
const numbers = [12, 35 ,35 , 2, 10, 10, 34, 12];
const number = [10, 10 , 10];
// Output: The second largest element is 34
console.log(findSecondLargestUsingIteration(numbers));
console.log(findSecondLargestUsingIteration(number));
Output
The second largest element is 34 No second largest element exists
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