How to find second largest element in an array in javascript
Answers
Answered by
1
Answer:
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);
Thanks for the question Dear.
Hope it helps you
Similar questions