Javascript Problems – Averaging an Array

This problem came from the Colt Steele Udemy JS Bootcamp.  He is introducing Node, and the problem is to average an array.   I had to review my array summing options.  I did it two ways — the first using the forEach() method, and the second using the reduce() method.

Once I have the sum of the array, I divide it by array.length to get the average.  I use Math.round() to round the number to the nearest integer.

function grader(scores) {
    
    let sum = 0
    
    // OPTION 1 - FOREACH METHOD
    scores.forEach(function(score) {
        sum += score;
    });
    
    // OPTION 2 - REDUCE METHOD
    // sum = scores.reduce(function(a,b) {
    //     return a+b;
    // }, 0);
    
    let avg = Math.round(sum / scores.length);
    console.log(avg, scores);    
    return avg;
}

grader([90,98,89,100,100,86,94]);
grader([40,65,77,82,80,54,73,63,95,49]);

 

Leave a Reply

Your email address will not be published. Required fields are marked *