Sports Game Example
const players = [
{
name: 'John',
position: 'forward',
goals: 10
},
{
name: 'Jane',
position: 'midfield',
goals: 5
},
{
name: 'Bob',
position: 'defense',
goals: 2
}
];
// Calculate the total number of goals scored by the team
let totalGoals = 0;
players.forEach(player => {
totalGoals += player.goals;
});
console.log(`Total goals scored: ${totalGoals}`); // Output: Total goals scored: 17
// Find the player with the most goals
let topScorer = players[0];
players.forEach(player => {
if (player.goals > topScorer.goals) {
topScorer = player;
}
});
console.log(`Top scorer: ${topScorer.name} (${topScorer.goals} goals)`); // Output: Top scorer: John (10 goals)
// Filter the players by position
const forwards = players.filter(player => player.position === 'forward');
console.log(`Forwards: ${forwards.map(player => player.name).join(', ')}`); // Output: Forwards: JohnLast updated