Is there a way to cease the counting?

Currently immersing myself in the world of JavaScript and taking on a challenging exercise. The task at hand involves creating a simulation game, with an object containing three arrays (representing each individual game).

Successfully managed to display the average score of the first game in the console, but facing difficulties when trying to do the same for the other two games. Despite setting the 'totalScore' variable to 0, the counting continues from the previous game's total.

For instance, the average score for the first game is 97.66. Ideally, I would want the average calculation for the second game to start fresh from 0, but it seems to carry over from the previous calculation. Any suggestions or alternative approaches to tackle this issue? Appreciate any insights 🙏🏽.

const dolphins = [
    [96, 88, 109], //Game1
    [80, 76, 120], //Game2
    [99, 100, 97] //Game3
]

let score = 0;

for (let i = 0; i < dolphins.length; i++) {
    let totalScore = 0; // Should it go out of the loop?
    const game = dolphins[i];
    console.log(`Game #${i + 1}`)
    for (let j = 0; j < game.length; j++) {
        score += game[j];
        totalScore = score / dolphins.length;
    }
    console.log(totalScore);
} 

Answer №1

Ensure let score = 0; is placed within the loop to guarantee it starts at 0 for every game.

Answer №2

Consider initializing

let points = 0

within the loop as well. By doing so, you ensure that the points reflect the current game status and do not carry over from previous iterations.

Answer №3

Ensure to always reset the "score" to zero after each loop iteration.

Consider renaming your "totalScore" variable to "averageScore."

const dolphins = [
    [96, 88, 109], //Game1
    [80, 76, 120], //Game2
    [99, 100, 97]  //Game3
]

let score = 0;
let averageScore = 0;

for (let i = 0; i < dolphins.length; i++) {
    const game = dolphins[i];
    
    console.log(`Game #${i + 1}`)
    
    for (let j = 0; j < game.length; j++) {
        score += game[j];
        averageScore = score / dolphins.length;
    }
    console.log(averageScore);
    score = 0;
} 

Answer №4

To easily accomplish this, you can utilize the Array.reduce() method.

Check out this demonstration:

const dolphins = [
    [96, 88, 109], //Game1
    [80, 76, 120], //Game2
    [99, 100, 97] //Game3
];

const avg = dolphins.map(arr => {
    return arr.reduce((a, b) => a + b) / arr.length;
});

console.log(avg);

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

Utilizing jQuery AJAX to send a post request to my ASP.NET webservice while using JSON.stringify

I am attempting to initiate a jQuery AJAX post to my ASP.NET webservice. However, when I access the strSubscriber.email variable in the subscribeToSearch method, it appears to be empty even though the method is executed. Why could this be happening? Befor ...

Implementing the React Router into a ReactJS project: Methods to prevent users from clicking on links within React-Router's <Link> component

I'm exploring React-Router's Link and have set up the following: <Link to={...}>{this.props.live? "Live": "Not Live"}</Link> In this configuration, if this.props.live is present, I want to display the text "Live" which will lead to ...

Can AngularJS functions be saved in arrays and then assigned to ng-click?

I have been attempting to create buttons using an Array in my code. While the buttons are displayed on the screen, the functions linked to each button in the array are not working as expected. var appModule = angular.module('app',[]); appModul ...

What makes changing styles via batch (cssText) in Chrome slower than changing them individually (.style.property)?

I recently came across some interesting tips in the "High Performance Javascript" book regarding optimizing for minimizing repaints and reflows. One of the suggestions was to batch DOM changes for better performance, such as utilizing: var el = document.g ...

What method can I use to ensure that the sidebar stays fixed at a particular div as the user continues to scroll down the

Is there a way to automatically fix the sidebar once the user scrolls down and hits the top of the .Section2? Currently, I have to manually enter a threshold number which can be problematic due to varying positions across browsers and systems. Fiddle htt ...

Javascript code fails to execute properly on IE8

I have a scenario where I am working with two drop-down menus. When the user selects an option from one menu, it should dynamically change the options in the other menu. However, I'm facing an issue with Internet Explorer where the second drop-down me ...

Struggling with setting up dynamic URL parameters in react-router

I'm working on generating dynamic URLs to display different content based on the URL parameters. When I include: <Route path="/example/:id" component={Example} /> and then visit /example/99 in my browser, I see an error message in th ...

Why doesn't the address bar automatically update to the correct path after successfully authenticating with NextAuth using credentials?

Is there a way to automatically refresh the URL path once a successful login is completed with credentials? I attempted to set up credential authentication similar to the guide provided by Next in their tutorial here. However, I am only using email for au ...

What is the best way to display a Bootstrap alert above all other elements on the page?

I need help with adjusting the placement of my bootstrap alert. Currently, when the input box value is not valid and the button is clicked, the alert shows up below the input box. I would like it to appear in the middle of the page, on top of the text box. ...

Troubleshooting: Mongoose's push method failing to add item

Currently, I am developing a Library Management application using Node.js for the backend and MongoDB as the database. The server is built on Express and utilizes the Mongoose library. When a client requests to issue a book, a POST request is sent, and the ...

Discovering Unnecessary CSS & JS Code

Currently, I am tackling a freelance project focused on upgrading a website. The client is requesting specific features from their old site be replicated on the new one. However, the challenge lies in the fact that the old site's CSS and JS are consol ...

Update various attributes of a div element using JavaScript

I have a progress bar in Bootstrap that receives data through a JavaScript function. Check out the progress bar below: <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" ...

Not utilizing layouts in express while retaining CSS styling

Struggling to figure out how to exclude my layout in express. I attempted: response.render("index",{layout: false}); However, this resulted in the css being disabled on the page. Am I overlooking something? What is the most effective method for disabling ...

Mastering the Javascript ++ and += Operators

I'm struggling with a simple movement engine I created. When the Up key is pressed, a function moves a small div up, and when the Down key is pressed, it does the opposite. I suspect the issue lies with the += in the Down() function, as changing it to ...

Can Mongoose be integrated into a Next.js API environment?

My current project involves creating a website for my sister to showcase and sell her artwork. Utilizing Next.js, I have set up the framework where the website displays the artwork by fetching an array from a database and iterating through it. Let's ...

Assessing string expressions within an object provided to an Angular directive

How can I evaluate string expressions in an object passed to a directive? I've reviewed various solutions but couldn't make it work as expected: Compiling dynamic HTML strings from database Dynamically add directive in AngularJS How to get eva ...

Utilize JavaScript conditions to dynamically apply styles within your web application

I am facing a challenge with managing two separate <style> tags that each contain a large number of styles and media queries. The issue is that one set of styles is intended for desktop users, while the other is meant for mobile users. When both se ...

Using Ajax to invoke a C# webmethod

I'm trying to call a webmethod defined in this specific class <%@ WebService Language="C#" Class="emt7anReyady.myService" %> using System; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System.Linq; usi ...

Creating a touch-like scrolling experience with CSS and the mouse

Is there a way to incorporate mouse scroll functionality in my Angular app similar to the scrolling feature on touch screen devices where you swipe left or right to navigate? I'm interested in implementing a scrolling technique that allows users to cl ...

pressure exerted on the body

Recently, I've been working on a project for the website . One of the main issues I've encountered is that the <body> element is consistently 20px lower than it should be at the top. This has led to visible problems with the background grad ...