January 23, 2020

Answer to JavaScript Arrays Exercise Q9

 

The following is the code for both parts (i) and (ii). The function for part (ii) appears first.

/*
This function takes an array of mountain name strings
and corresponding heights.
[name1 , height1, name2, height2 ...etc].
Returns the name of the highest mountain,
*/
function getHighestName(anArray)
{
  var highest, highestName;
  highest = anArray[1];
  highestName = anArray[0];
  for (var j = 3 ; j < anArray.length; j = j + 2)
  {
    if (anArray[j] > highest)
    {
      highest = anArray[j];
      highestName = anArray[j - 1];
    }
  }
  return highestName;
}
//Answer to part(i)
var name, height, mountains, index;
mountains = new Array();
index = 0;
while (mountains.length < 10) //or index < 10
{
  name = window.prompt('Enter name of mountain','');
  mountains[index] = name;
  height = window.prompt('Enter height in metres','');
  height = parseInt(height);
  mountains[index + 1] = height;
  index = index + 2;
}
//display a list of names in a single box
//initialize a string
var displayStr = '';
for (var i = 0; i < mountains.length; i= i + 2)
{
  displayStr = displayStr + mountains[i] + '\n';
}
window.alert('The list of mountains is:' + '\n' + displayStr);
//now for part (ii)
//call the function
var highName = getHighestName(mountains);
//display name of highest mountain and its height
window.alert('The highest mountain is ' + highName);

//You could call the function inside the argument to the alert box
//window.alert('The highest mountain is ' + getHighestName(mountains));

Notes:

  • There are alternatives to the above
    The array can be declared with
    mountains = new Array(10);
    However, if you do this, you cannot use the condition mountains.length < 10 and will need to write
    while(index < 10)
    {
      //etc
    }

 

Back « JavaScript arrays exercise

 

 

 

 

 

 

 

 

Up to top of page