Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

finding the average of an array with a for loop in a function

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// * 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]));

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading