How to use Array.slice and Array.sort In Javascript
Using Array.slice creates a copy of the array, which is then sorted using Array.sort. The second largest element is accessed by index `[1]` from the sorted array.
Example : In this example we creates a sorted copy of an array in descending order using slice() and sort(). It then retrieves the second largest element by accessing the second index.
const array = [10, 5, 20, 8, 15];
const sortedArray = array.slice().sort((a, b) => b - a);
const secondLargest = sortedArray[1];
console.log("Second largest element:", secondLargest);
Output
Second largest element: 15
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