jsRant asked this 4 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 4 years ago
24 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 3 years ago
7 likes
if i want to see 3rd highest array then how to write 
Guest 1 year ago
3 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 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]));

Luka 2 years ago
3 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
1 like

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

Guest 1 year 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| 4 months ago