Find The Second Largest Element In An Array Using A Single Loop In JavaScript

Umar Farooque Khan
2 min readJul 10, 2023

--

To find the second largest element in an array using a single loop in JavaScript, you can iterate over the array and keep track of the largest and second-largest elements as you go.

Example:

function findSecondLargest(arr) {
let largest = arr[0];
let secondLargest = -Infinity;
for (let i = 1; i < arr.length; i++) {
if (arr[i] > largest) {
secondLargest = largest;
largest = arr[i];
} else if (arr[i] < largest && arr[i] > secondLargest) {
secondLargest = arr[i];
}
}
return secondLargest;
}
// Example usage:
const array = [5, 2, 10, 8, 3];
const secondLargest = findSecondLargest(array);
console.log("Second largest element:", secondLargest);

Output:

Explanation:

This code defines a function findSecondLargest that takes an array arr as its parameter and returns the second largest element in that array. It follows these steps:

  1. It initializes two variables: largest and secondLargest.
  • largest is assigned the value of the first element of the array arr[0].
  • secondLargest is assigned the value of negative infinity (-Infinity).

2. It then iterates over the array starting from the second element (i = 1) up to the last element (i < arr.length).

3. Inside the loop, it compares each element of the array with the current largest value.

4. If the current element is greater than the largest value, it means we have found a new largest element. In this case:

  • The previous largest value becomes the new secondLargest value.
  • The current element becomes the new largest value.

5. If the current element is smaller than the largest value but greater than the secondLargest value, it means we have found a new second largest element. In this case:

  • The current element becomes the new secondLargest value.

6. Finally, the function returns the value of secondLargest.

In the example usage, the function is called with an array [5, 2, 10, 8, 3] and the second largest element is determined. The result is then printed to the console using console.log.

Here are some additional high-quality tutorials for you to explore:

  1. Unraveling JavaScript Design Patterns
  2. JavaScript interview Question and Answer
  3. Node Js Interview Question and Answer
  4. JavaScript Tricky Question

If you enjoyed this article, please give it a round of applause and consider following me for support!

--

--

Umar Farooque Khan

Experienced software developer with a passion for clean code and problem-solving. Full-stack expertise in web development. Lifelong learner and team player.