2

So I want to return true if myScore is higher than classScore average but it keeps returning false. This is what I came up with.

function compareScore(classScore, myScore) {

  var classAverage = 0;

  for(var i = 0; i < classScore.length; i++){
    classAverage = (classAverage / classScore.length) + classScore[i];
  };

  if(myScore > classScore){
    return true;
  } else {
    return false;
  }
}

console.log(compareScore([20,20,20],70))

2 Answers2

1

You need to compare classAverage not the array classScore. And also the correct way to calculate average is get sum of array and then divide it by length of array.

In below case you don't need to use if else just simply return the result of logical operation.

function compareScore(classScore, myScore) {
  let classSum = 0;

  for(var i = 0; i < classScore.length; i++){
    classSum += classScore[i];
  };
  let classAverage = classSum/classScore.length
  return myScore > classAverage;
}

console.log(compareScore([20,20,20],70))

Another way of doing that is to use reduce()

const compareScore = (classScore, myScore) => classScore.reduce((ac, a) => ac + a, 0)/classScore.length < myScore

console.log(compareScore([20,20,20],70))
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
  • quick note on your example that uses reduce, you could use `classScore.reduce((ac,a, i, arr)=> ac + (a/arr.length), 0)` to get the average without needing to do the division at the end. – Jhecht Mar 06 '20 at 19:24
0

you could youse Array.reduce() to get the sum and go from there.

function compareScore(classScore, myScore) {
      var sum = classScore.reduce((previous, current) => current += previous);
      var average = sum / classScore.length;

      if(myScore > average){
        return true;
      } else {
        return false;
      }
    }

    console.log(compareScore([20,20,20],70))
  • 1
    Two things: The compound assignment `+=` isn't necessary since the function's return value is what's used, not `current`, so `+` is sufficient there. Secondly, you need to specify an `initial` value of `0` so that empty arrays won't throw an exception. Of course, both of these points have already been addressed in the existing answer, so yours doesn't add anything helpful. – Patrick Roberts Mar 06 '20 at 18:32