Find the second largest number in a array

function findSecondLargest(arr) {
  // Sort the array in descending order
  arr.sort(function(a, b) {
    return b - a;
  });

  // Return the element at index 1 (the second largest)
  return arr[1];
}

// Example usage
const numbers = [10, 5, 8, 20, 15];
const secondLargest = findSecondLargest(numbers);
console.log("The second largest number is:", secondLargest);
Output:

The second largest number is: 15

Execute above code here

0
Subscribe to my newsletter

Read articles from Hari Krishna Anem directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Hari Krishna Anem
Hari Krishna Anem

Full stack developer (ReactJS, NodeJS, JavaScript, PHP, SQL)