How can I make it stop counting?

Viewed 60

I'm currently learning JS and I was trying to do this exercise. This is a simulate game, where I created an object with three arrays (each representing one game, so there's 3 games).

I managed to print in the console the first game average score and I want to do the same with other two games, but it keeps counting.

For example, average for 1st game is 97.66, I want it starts counting for the second game from 0 but instead it starts counting from 97.66, I thought giving a value to the 'totalScore' variable of 0 was going to fix it but it didn't.

What could I do or how would you change the code? Would you use another way? Thank you .

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);
} 
4 Answers

Move let score = 0; to inside the loop, so that it gets initialized with 0 at the start of each game.

try initialising

let score = 0

inside the for loop too. Since score contains previous game value, so it starts from 97.66 only.

You never set the "score" back to 0 at the end of each loop.

Shouldn't your "totalScore" be an "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;
} 

You can simply achieve it by using Array.reduce() method.

Live Demo :

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);

Related