0

I'm building an array of players which will be added to when solver is not found within the name properties inside players

let players = []

let solver = 'Any Name Given'

// This if statement is the issue : How to check the name properties and compare to solver 
// If the solver's name is already in players : add +1 point
if(players.includes(solver)){

   // Give The Player +1 point

   return console.log('Player Exists')

 } else {

   // Add The newPlayer to players with a starting point 
   let newPlayer = [name = solver, points = 1]
   players.push(newPlayer)

}

How do I compare solver inside name of players. I've tried players[name] and players.name with no luck

1 Answer 1

1

In your else, you should be having:

const newPlayer = {name: solver, points: 1};

i.e. an object, rather than an array. So that you have players array which will always have player objects

Now, since what you have is an array of objects, you need to use something like some to find whether an object matching your condition exists or not:

The if condition can be replaced by:

if (players.some(player => player.name === solver))

I just saw that you want to increase the points of the found player by 1. In that case you should be using find instead of some so that you can access the found player and update its points property. So do this:

const player = players.find(player => player.name === solver);

if (player) {
    player.points++;
} else {
    const newPlayer = {name: solver, points: 1};
    players.push(newPlayer)
}

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Now the only question left is how can I get the points property of the existing object in the if statement to add a point
@Elitezen Saw that part of question late, Updated the answer to show how you can increment points property of the found player.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.