This program is to find second largest element in an array in Javascript.
Step 1: Initialize two variables max and second to array[0].
Step 2: First We find the max element by traversing in array and comparing elements we get max element.
Step 3: In next loop we again traverse in array and compare the variables(max and second) with array elements to find the second largest number
PROGRAM :
// Given Array
let array=[1,2,31,10,27,20]
let max=second=array[0];
// finding the max element
for(let i=0;i<array.length;i++){
if(array[i]>max){
max=+array[i];
}
}
// find the second largest
for(let i=0;i<array.length;i++){
if(second<(+array[i]) && (+array[i])<max){
second=array[i];
}
}
console.log("Second largest number is",second)