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
19 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);
Luka 1 year ago
5 likes
if i want to see 3rd highest array then how to write 
Guest 6 months 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]));

Luka 1 year 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

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