jsRant asked this 2 years ago

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?


ben100 2 years ago
13 likes

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

var biggest = myArray[0];
var nextbiggest = myArray[0];
    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);

Guest 1 year ago
3 likes

if i want to see 3rd highest array then how to write 

Guest 9 months ago
1 like

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

var biggest = myArray[0];
var nextbiggest = myArray[0];
    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);

Guest 2 months ago
1 like

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]));