skip to Main Content

I’m trying to find the average value of the array, I’m stumped on how to add the array values together, I have the for loop condition set up ( for ( i = 0; i < array.length; i++)

but how do I add the array values together ??

instructions:

// * PART 1
// * Return the average value for the given array of numbers.
// * Example: getAverage([22, 45, 4, 65]) => 34
// * */

where I’m at:

    function getAverage(array) {    
      for ( let i = 0; i < array.length; i ++){
      let total =              <-How do I add them together to get the total?
       return total / array.length
     } 

    }

    console.log(getAverage([20, 22, 24, 26]));

2

Answers


  1. You want the + operator.
    Create a variable outside of your loop, set it to 0, and add the value each time.

    function getAverage(array) {
        let total = 0;
        for (let i = 0; i < array.length; i++) {
            total += array[i];
        }
        return total / array.length;
    }
    
    Login or Signup to reply.
  2. This is the perfect opportunity to use a reducer.

    function getAverage(array) {
        return array.reduce((sum, item) => sum + item, 0) / array.length;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search