<html>
<head>
<script language="javascript" type="text/javascript">
function findSecondHighestNumberInArray(sequence) {
var secondHighestNumber = 0;
/* Sort the sequence passed to this function */
sequence.sort(function(a, b) {return a - b});
/* Trap single element array */
if (sequence.length <= 1) {
window.alert("The array does not contain multiple elements.");
}
else {
/* Remove potential duplicate element values from array */
var sequenceMod = [];
for (var o = 0; o < sequence.length; o++) {
if (o < (sequence.length - 1)) {
if (sequence[o] != sequence[(o + 1)]) {
sequenceMod.push(sequence[o]);
}
}
if (o == (sequence.length - 1)) {
if (sequence[o] != sequenceMod[(sequenceMod.length - 1)]) {
sequenceMod.push(sequence[o]);
}
}
}
/* Trap insufficient number of elements, otherwise return second highest value present */
if (sequenceMod.length <= 1) {
window.alert("Insufficient number of unique elements.");
}
else {
var highestValue = sequenceMod[sequenceMod.length - 1];
var secondHighestValue = sequenceMod[sequenceMod.length - 2];
secondHighestNumber = secondHighestValue;
}
}
return(secondHighestNumber);
}
</script>
</head>
<body onload='javascript:document.getElementById("output").value = findSecondHighestNumberInArray([1,2,3,4,5,6]);'>
Given the array sequence: [1,2,3,4,5,6] find the second highest number.<br />
<span style="font-size:9pt">For reference, the second highest number returned should be: 5</span>
<br /><br />
<strong>Function Logic Output:</strong><br />
<textarea name="output" id="output" rows="4" cols="30"></textarea>
</body>
</html>