This code is supposed to return the second largest number in the array. However I notice that this code does not work if there are duplicate elements in the array. It returns the largest number as the second largest number when I set the array equal to [2, 3, 6, 6, 5]. It is supposed to return 5 as the second largest and the 6 is the first largest.
I added portion of code in the else if to see if I can delete a duplicate but it didn't work it is still returning 6 instead of 5.
const nums = [2, 3, 6, 6, 5];
function getSecondLargest(nums) {
var firstLargest = nums[0];
var secondLargest = nums[0];
for(var i = 1; i < nums.length; i++){
if (nums[i] > secondLargest){
secondLargest = firstLargest;
firstLargest = nums[i];
}
else if ((secondLargest === nums[i]) || (firstLargest === nums[i])){
delete nums[I];
}
else{
nums[i] = secondLargest;
}
}
return secondLargest;
} console.log(getSecondLargest(nums));
nums=[], has only one valuenums=[5]or contains only one kind of numbernums=[5,5,5,5,5]?