Home > Back-end >  Trying to get the average value of the elements, please help ! JavaScript
Trying to get the average value of the elements, please help ! JavaScript

Time:12-14

My assignment is to Implement the getSpeedStatistic function, that accepts the testResults array and returns statistics as an array with 3 numbers:

the first one is the lowest value; the second is the highest value; the last one is the average value, rounded down

My function:

function getSpeedStatistic(testResults) {
  let min = testResults[0];
  let max = testResults[0];
  let sum = 0;
  let average = 0;

  for(const number of testResults){

    if(number > max){
      max = number;
    };

    if(number  < min){
      min = number;
    };

    sum  = number;
    average  = Math.round(sum / testResults.length);
  };
  return [min, max, average];
};

It works for the lowest and highest value but it doesnt return the right average, i cant seem to find a pattern for the results either, it seems like it gives me random numbers, i dont understand the issue. For example:

It should return [0, 8, 3] when input is [5, 0, 8, 1] - but it returns [0,8,9];

Should return [1, 18, 4] when input is [1, 2, 2, 3, 3, 3, 3, 18] - but it returns [1,18,11].

Should return [1, 9.2, 5] when input is [4.5, 6.7, 9.2, 1] - but it returns [1,9.2,14]

Please help !

CodePudding user response:

You can try this code:

function getSpeedStatistic(testResults) {
 let lowest = testResults[0]
 let highest = testResults[0]
 let sum = 0
testResults.forEach (num => {
    if (num < lowest){
       lowest = num
    }
    else if (num > highest){
       highest = num
    } 
    sum  = num
 })

 return [lowest, highest, Math.floor(sum/testResults.length)]
};

console.log(getSpeedStatistic([5, 0, 8, 1])) // Example

In the forEach loop each time we check if the value is less than lowest variable if yes we equal that to the new number and this process is the same for defining the highest number but we check if number is higher than highest variable.

Each time we sum the number in the loop in sum variable and when we want to output the result we simply divide that by the length of the array (average) and then floor it to round it down.

CodePudding user response:

Put the average outside and after the for loop

function getSpeedStatistic(testResults) {
  let min = testResults[0];
  let max = testResults[0];
  let sum = 0;
  let average = 0;

  for(const number of testResults){

    if(number > max){
      max = number;
    };

    if(number  < min){
      min = number;
    };

    sum  = number;

  };
    average  = Math.round(sum / testResults.length);
  return [min, max, average];
};
  • Related