In: Computer Science
Define a function in Javascript named secondHighest which accepts an array of numbers, and returns the second highest number from the array. If the highest value occurs more than once, then it is also the second highest (see example). Assume the input array will always have length at least two (so there is always a second highest value).
The original array must NOT be modified by this function.
Example
secondHighest([5,3,8,6,2,7,4]) must return 7, and
secondHighest([5,3,8,6,2,7,8]) must return 8.
I have the Python code but I am having trouble converting it to Javascript format
def secondHighest(number):
count = 0
A1 = A2 = float('-inf')
for b in number:
count += 1
if b > A2:
if b >= A1:
A1, A2 = b,A1
else:
A2 = b
return A2 if count >= 2 else None
print(secondHighest([5,3,8,6,2,7,4]))
print(secondHighest([5,3,8,6,2,7,8]))
Code:
function myFunction(numbers) {
max1=0 //max is used to store highest element and initially 0
max2=0 //max is used to store second highest element and initially 0
for(i=0; i<numbers.length; i++) //traverse till length of given array
{
if(numbers[i] >= max1) //check if maximum is greater than curren element
{
max2 = max1; //then maximum is second maximum
max1 = numbers[i]; //and maximum element is current element
}
else if(numbers[i] >= max2 && numbers[i] <= max1) //if the element is greater than second max and lessthan max
{
max2 = numbers[i]; //then store it in second maximum
}
}
if(max1===max2) //if max1 and max2 are same then array has 2 maximum numbers
console.log(max1) //so print maximum number
else
console.log(max2) //otherwise print second maximum number
}
myFunction([5,3,8,6,2,7,4]); //call myFunction function
myFunction([5,3,8,6,2,7,8]);
Output:
.