What could be the reason for this function failing to calculate the mean of a set of data points?

I'm facing a challenge with this beginner problem.

"A task for you: Calculate the average score of a class whose test scores have been graded by a teacher.

Your mission is to complete the getAverage function, which receives an array of test scores and calculates the average score.

The average score is determined by adding up all the individual scores and dividing by the total number of scores.

average = sum of all scores / total number of scores I've provided a couple of function calls so that you can test your code as well.

Pointers:

You can utilize a loop to iterate over the scores array and sum up all the scores. Utilize the length property to find out the total number of scores."

This is the code snippet that I crafted:

function getAverage(scores) {
    let sum = 0;
    for (let i = 0; i < scores.length; i++) { sum += scores[i]; }
}

console.log(getAverage([92, 88, 12, 77, 57, 100, 67, 38, 97, 89]));
console.log(getAverage([45, 87, 98, 100, 86, 94, 67, 88, 94, 95]));

I'm encountering issues with it. Can you help me understand why?

I expected this function to iterate through the getAverage array, sum up the values, and present the average result.

Answer №1

Your code seems to be missing the part where you return the average of the scores calculated. It is important to divide the total sum by the number of scores in order to get the correct average value. To rectify this issue, make sure to add the division step after summing up all the scores inside the loop and return the result as the output of the getAverage function. One effective way to do this is by following these steps:

Code Section

This updated code accurately computes the total sum of the scores, divides it by the count of scores to determine the average, and then returns this calculated average value. By incorporating the necessary line for calculating and returning the average, the getAverage function will now perform correctly with various sets of scores.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Efficiently handling jsonwebtoken errors in node and express

Here is the verification function I've created: exports.verifyToken = function(req, res, next){ var token = req.body.token; jwt.verify(token, config.sessionSecret, function(err, decoded) { if(err){ return next(err); }else{ ...

ReactJS Enhancements: Additional Selection Feature

Is there a way to access both {board.id} and {board.name} properties in my select value? I tried using example={board.name} but it didn't work. handleChange(event){ this.setState({value: event.target.value}); this.setState({examp ...

Executing two nested loops with a delay in jQuery

I am currently working on a script that sends an ajax post to another page. I need to run two for loops before sending the ajax request with a timeout. The first loop is successful, but when I try to run the second loop, all requests are sent at the same ...

Changing the style of opening curly braces in JavaScript code styling

I have a piece of JavaScript code written for Vue that I would like to discuss. It is common practice in the JavaScript world to place the opening curly brace at the end of a line of code. <script> export default { name: 'newUser', data ...

Verify in PostgreSQL if every element in the array is present in a longer string

I am dealing with an array of strings in PostgreSQL: SELECT ARRAY['dog', 'cat', 'mouse']; Additionally, I have a lengthy paragraph describing the interactions between dogs and cats: Dogs and cats have a range of interaction ...

tips for incorporating async/await within a promise

I am looking to incorporate async/await within the promise.allSettled function in order to convert currency by fetching data from an API or database where the currency rates are stored. Specifically, I want to use await as shown here, but I am unsure abou ...

When importing data from a jQuery AJAX load, the system inadvertently generates duplicate div tags

Currently, I am utilizing a script that fetches data from another page and imports it into the current page by using the .load() ajax function. Here is the important line of code: $('#content').load(toLoad,'',showNewContent()) The issu ...

Troubleshooting error in data structure for nested dynamic routes with Next.js getStaticPaths

I am working on a page called [categories][price].js and I am attempting to achieve a particular data structure within the getStaticPaths function. For example, I want to have paths like cat1/10, cat1/20, cat1/30, cat2/10, cat2/20, etc. I came across this ...

Leveraging ajax for showcasing page content in a floating div container

I am in need of creating a button on my page that, when clicked, will display a floating div above the page and load another internal page. I believe this can be achieved using Ajax, but I have no experience with it and don't know where to start. Her ...

What are some ways to customize the appearance of React Semantic components?

Is there a way to apply CSS for react semantic UI when using create react app? I have installed semantic-ui-react and included the CSS CDN: loginForm.js: import React from "react"; import { Button, Form, Header } from "semantic-ui-react"; import styles f ...

Getting values from a JSON array in Swift 4 - a step-by-step guide

I have the following code snippet written in Swift 4 using Alamofire: Alamofire.request("http://xxxx.pl/id=1", method: .get, parameters: nil) .responseJSON { response in let jsonResponse = JSON(response.result.value!) let resData = jsonRespon ...

Dividing internal CRUD/admin panel from the live application

Currently developing a moderately complex react app with redux. We have a production version that meets our requirements and now we are working on an administrative area for a local version of the application. This local version will only have basic CRUD f ...

Is ASP.NET capable of displaying an expandable grid view?

After searching online, I have yet to find a solution that meets my requirements. Currently, my DB view generates the following data: --------------------------------------------------- Company | Code | Total | Available | Used | Needed ---------------- ...

Effortlessly sending multiple forms on a single page via POST in Express JS without the need for page refresh

I am creating a new application using ExpressJS and I want to include the following HTML code in a jade file. On one of my pages, I have 4 form buttons: <div class="dog"> <div class="dog_wrapper clearfix"> <div cla ...

Incorporate JavaScript files into your Gruntfile

I utilized a bootstrap-compass project by using the yeoman generator provided in this link: https://www.npmjs.com/package/generator-bootstrap-compass You can view the file structure through the link mentioned above. Now, I am looking for guidance on cor ...

Ways to update the select field without having to reload the entire page

I am working on a unique feature that involves two levels of drop down menus. When a user makes a selection in the first level, a corresponding set of options will appear in the second level. For example, I have 6 options in the first level, each with its ...

Browser crashing due to drag-and-drop upload of desktop images

I've set up a form for uploading images using ajaxForm. I added a feature where users can drag and drop photos from their desktop (HTML5 drag & drop). Everything works smoothly when the photo is small, around 2mb. However, an issue arises when attempt ...

Is jQuery validation compatible with mobile phone numbers?

Is there a way to verify an Iranian mobile phone number using jQuery with the input:text? Iranian mobile phone numbers follow a specific numeral system, such as: 091- --- ---- 093[1-9] --- ---- 092[1-9] --- ---- 090[1-9] --- ---- Here are some example pr ...

"Ensure that all necessary fonts and assets are included in the development of your Vue component

At the moment, I am utilizing vue-cli-service build --target lib --name myLib [entry] to compile Vue into a component library for integration into other projects. Nevertheless, it only produces four files which are: dist/myLib.umd.min.js dist/myLib.umd. ...

Having issues with the print_r function not displaying all the values as expected

When I need to send an email via PHP, I find it helpful to fill an array with the body content. This way, it's easier to quickly comment out something if needed. Here is an example of how I structure this array: $emailContentArray = array(); $email ...