Average, Maximum and Minimum

Three algorithms worth knowing

These three come up in almost every program that handles a list, and all three are the same shape: one loop over the list, and one variable that outlives it.
• Find the sum of a list of numbers.
• Find the average of a list of numbers.
• Find the maximum or the minimum of a list of numbers.
Learn the shape once and the rest is variation.

Summing a list inside a function

A loop that adds up a list deserves a name. Wrap it in a function and the rest of your program can ask for a sum without writing the loop again.

Average

The average is the sum divided by how many numbers there are, and nums.length supplies that count. The body is the summing loop you already have. Only the last line is new, and where it sits matters: the division belongs OUTSIDE the loop, so it happens once, after the whole sum has been built.

Adding only some of the values

Same loop, one extra decision inside it. Visit every value, but only add the ones that pass the test. Everything the loop skips is still visited, it just never reaches the accumulator.

Finding the maximum

Walk the list holding on to the largest value seen so far, and replace it whenever something bigger turns up. Does this version work?
Start the running maximum at the first value of the list instead. Then the answer is always a value that came from the data, whatever the data happens to be.
The program below finds the average and the highest of four overnight temperatures, all below freezing. Run it, then change it and run it again:
• Delete the last temperature, -1, from the array.
• Press Reset, then change let best = nums[0]; to let best = 0;.
• Keep that change, and add 4 to the end of the array.
function mean(nums) {
  let t = 0;
  for (const n of nums) {
    t += n;
  }
  return t / nums.length;
}

function highest(nums) {
  let best = nums[0];
  for (const n of nums) {
    if (n > best) { best = n; }
  }
  return best;
}

let overnight = [-3, -13, -7, -1];
console.log("Average:", mean(overnight));
console.log("Highest:", highest(overnight));
Output
Press Run to see what this program prints.

Note: This IDE is for experimenting with the code in this lesson. Your changes are not saved, and refreshing the page puts back the original lesson code.