Main Page
 The gatekeeper of reality is
 quantified imagination.

Stay notified when site changes by adding your email address:

Your Email:

Bookmark and Share
Email Notification
findSecondHighestNumberInArray [Go Back]
Purpose
The purpose of this script is to find the second highest number in an array (sorted or unsorted, with or without duplicated numbers). Over the decades of programming I've never needed to solve such a task but I was asked about it so I provide one approach (using javascript) below.

The Second Highest Number Question (and answer):
Given the array sequence: [1,2,3,4,5,6] find the second highest number.
For reference, the second highest number returned should be: 5

Function Logic Output:


Full Working Code You Can Copy:
<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>
About Joe