# Javascript: find second largest value in an array?

Sample:

myArray = [1, 2, 4, 10, 20,100]

How to find second largest value without sorting the array or latering its contents?

4 years ago
26 likes

This can be done in one pass in a for loop.

``````var biggest = myArray;
var nextbiggest = myArray;
for(var i=0;i<myArray.length;i++){
if(myArray[i]>biggest){
nextbiggest = biggest;
biggest = myArray[i];
}
else if(myArray[i]>nextbiggest && myArray[i]!=biggest)
nextbiggest = myArray[i];
}

console.log(nextbiggest);``````
3 years ago
8 likes
if i want to see 3rd highest array then how to write
1 year ago
4 likes

If you pass the var myArray = [10,10,10,5,6,7,8]; then the second highest to be 8 not 10.Getting wrong output in given array.

2 years ago
3 likes

let secondMax = (input) =>{

let max = Math.max.apply(null,input)

input.splice(input.indexOf(max),1)

max=Math.max.apply(null,input);

return max;

}

console.log(secondMax([10,20,30,40,50]));

2 years ago
3 likes

This can be done in one pass in a for loop.

``````var biggest = myArray;
var nextbiggest = myArray;
for(var i=0;i<myArray.length;i++){
if(myArray[i]>biggest){
nextbiggest = biggest;
biggest = myArray[i];
}
else if(myArray[i]>nextbiggest && myArray[i]!=biggest)
nextbiggest = myArray[i];
}

console.log(nextbiggest);``````
1 year ago
1 like

function secondLargest(arr) {

var max1st = arr;

var max2nd = 0;

for(var i=0; i<arr.length; i++) {

if(arr[i] > max1st) {

max2nd = max1st;

max1st = arr[i];

}

else if(arr[i] > max2nd && arr[i] !== max1st) {

max2nd = arr[i];

}

}

return max2nd;

}

console.log(secondLargest([100,2,4,54,27,98,99]));

console.log(secondLargest([10,22,48,54,27,8]));

console.log(secondLargest([2,4,54,27,98,99]));

console.log(secondLargest([21,42,87,27,8,99]));

2 years ago

Find the third largest number in an array given an array of numbers with at least a size `3` without sorting. in Javascript

-

If I put the largest number first then I can't find the right answer.

8 months ago