Example 1: get highest value from array javascript
//For Values
var arr =[1,10,3]
var min = Math.min.apply(null, arr),
max = Math.max.apply(null, arr);
//For Objects
var arr = [{a: 1},{a: 10},{a: 3}]
var values = arr.map(val => val.a);
var max = Math.max.apply(null, values);
console.log(max)
Example 2: find second largest number in array javascript
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
};
Example 3: find highest number in array javascript
function findHighestNumber(nums) {
let inputs = nums.filter((val, i) => nums.indexOf(val) === i)
let max = Math.max(...nums);
let min = Math.min(...nums);
return max + (-min);
}
console.log(difference([1, 7, 18, -1, -2, 9]));
Example 4: second largest value in array java 8
public class ThirdLargestNumberInAnArray {
public static void main(String args[]){
int temp, size;
int array[] = {10, 20, 25, 63, 96, 57};
size = array.length;
for(int i = 0; i<size; i++ ){
for(int j = i+1; j<size; j++){
if(array[i]>array[j]){
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
System.out.println("Third second largest number is:: "+array[size-2]);
}
}
Example 5: find second largest number in array javascript
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;
};
Example 6: find second max element in array in 1 iteration
/**
* C program to find second largest number in an array
*/
int main()
{
int arr[MAX_SIZE], size, i;
int max1, max2;
/* Input size of the array */
printf("Enter size of the array (1-1000): ");
scanf("%d", &size);
/* Input array elements */
printf("Enter elements in the array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}
max1 = max2 = INT_MIN;
/*
* Check for first largest and second
*/
for(i=0; i<size; i++)
{
if(arr[i] > max1)
{
/*
* If current element of the array is first largest
* then make current max as second max
* and then max as current array element
*/
max2 = max1;
max1 = arr[i];
}
else if(arr[i] > max2 && arr[i] < max1)
{
/*
* If current array element is less than first largest
* but is greater than second largest then make it
* second largest
*/
max2 = arr[i];
}
}
printf("First largest = %d\n", max1);
printf("Second largest = %d", max2);
return 0;
}