var secondMax = function (){
var arr = [20, 120, 111, 215, 54, 78]; // use int arrays
var max = Math.max.apply(null, arr); // get the max of the array
arr.splice(arr.indexOf(max), 1); // remove max from the array
return Math.max.apply(null, arr); // get the 2nd max
};
javascript find the second highest Element from array
var secondMax = function (){
var arr = [20, 120, 111, 215, 54, 78]; // use int arrays
var max = Math.max.apply(null, arr); // get the max of the array
arr.splice(arr.indexOf(max), 1); // remove max from the array
return Math.max.apply(null, arr); // get the 2nd max
};
var secondMax = function (arr){
var max = Math.max.apply(null, arr), // get the max of the array
maxi = arr.indexOf(max);
arr[maxi] = -Infinity; // replace max in the array with -infinity
var secondMax = Math.max.apply(null, arr); // get the new max
arr[maxi] = max;
return secondMax;
};
How would you find the second largest number in an array?
// Java program to find second largest
// element in an array
import java.util.*;
class GFG{
// Function to print the
// second largest elements
static void print2largest(int arr[],
int arr_size)
{
int i, first, second;
// There should be
// atleast two elements
if (arr_size < 2)
{
System.out.printf(" Invalid Input ");
return;
}
// Sort the array
Arrays.sort(arr);
// Start from second last element
// as the largest element is at last
for (i = arr_size - 2; i >= 0; i--)
{
// If the element is not
// equal to largest element
if (arr[i] != arr[arr_size - 1])
{
System.out.printf("The second largest " +
"element is %d
", arr[i]);
return;
}
}
System.out.printf("There is no second " +
"largest element
");
}
// Driver code
public static void main(String[] args)
{
int arr[] = {12, 35, 1, 10, 34, 1};
int n = arr.length;
print2largest(arr, n);
}
}
// This code is contributed by gauravrajput1