I have a simple JavaScript program to calculate the winner of an election.
I use a FOR loop to assign the total of each candidates votes into a new array called totalVotesArray, I then output the corresponding candidates names and total votes into the browser window.
I then need to output the highest scoring candidate – I’ve used another FOR loop but I’m not sure I’ve done that part correctly. I’m stuck finding the index of the winning score and relating that the corresponding position in the parallel array.
Anyone know how I do this?
<HTML>
<HEAD>
<TITLE>
Election Results
</TITLE>
<LINK REL="stylesheet" TYPE="text/css" HREF="tma03.css">
<script type="text/javascript">
var candidateArray = ['Ms A Brown .......',
'Mr C Smith .......',
'Ms F Patel .......',
'Ms B Jones .......',
'Mr E Williams...',
'Mr D Johnson ....',
'Ms G Taylor'];
var onlineVotesArray = [41,37,43,11,59,21,36];
var paperVotesArray = [22,3,15,11,7,1,18];
//initialises totalVotesArray with a new empty array the same size as candidateArray
var totalVotesArray = new Array(candidateArray.length)
//for loop counts the number of times the addition of the online and paper votes should be performed
for (var i = 0; i <= candidateArray.length; i = i + 1)
{
/*adds elements at the position in the onlineVotesArray Array to the element in the same position in the paperVotesArray Array, and stores result in corresponding position in the total votes array */
totalVotesArray[i] = onlineVotesArray[i] + paperVotesArray[i];
}
//outputs the election report heading and results to the browser document window
document.write('Eatanswill Historical Society By Election' + '<BR>' + 'Declaration of Results' + '<BR>' + '<BR>');
document.write(candidateArray[0] + totalVotesArray[0] + '<BR>');
document.write(candidateArray[1] + totalVotesArray[1] + '<BR>');
document.write(candidateArray[2] + totalVotesArray[2] + '<BR>');
document.write(candidateArray[3] + totalVotesArray[3] + '<BR>');
document.write(candidateArray[4] + totalVotesArray[4] + '<BR>');
document.write(candidateArray[5] + totalVotesArray[5] + '<BR>');
document.write(candidateArray[6] + totalVotesArray[6] + '<BR>');
//this outputs an extra line break
document.write('<BR>');
//debugger;
var maximumTotalVoteIndex = 0;
for (var count = 1; count < totalVotesArray.length; count = count + 1)
{
if (totalVotesArray[count] > maximumTotalVoteIndex)
{
maximumTotalVoteIndex = totalVotesArray[count];
}
}
document.write( **THIS IS THE BIT I'M STUCK WITH** + ' is declared the winner');
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
try like this