jsRant asked this 7 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?


Best Answer by Guest 4 years ago

function secondLargest(arr) {
  var max1st = arr[0];
  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]));
console.log(secondLargest([10,10,10,5,6,7,8]));

Output

99
48
98
87
8
ben100 7 years ago
32 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 6 years ago
11 likes
if i want to see 3rd highest array then how to write 
Guest 4 years 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.

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

Guest 1 year ago
2 likes
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 5 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.

| Guest| 3 years ago