How to use Sorting In Javascript
Sort the array in ascending order and iterate through the sorted array from the end to find the first element different from the largest element, which is considered the second largest. If no such element is found, it indicates that there is no second-largest element.
Example: In this example The function findSecondLargest() determines the second largest element in an array by sorting it and returning the second element from the end, handling special cases.
function findSecondLargest(arr) {
let first, second;
// There should be at least two elements
if (arr.length < 2) {
return "Invalid Input";
}
// Sort the array in ascending order
arr.sort();
// Start from the second last element as
// the largest element is at last
for (let i = arr.length - 2; i >= 0; i--) {
// If the element is not equal to the
// largest element
if (arr[i] !== arr[arr.length - 1]) {
return "The second largest element is " + arr[i];
}
}
return "There is no second largest element";
}
// Driver program to test the function
const arr = [12, 35, 10, 35, 10, 34, 1];
// Output: The second largest element is 34
console.log(findSecondLargest(arr));
Output
The second largest element is 34
Time Complexity: O(n log 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