Search code examples
javascriptarraysinclude

Comparing Given String To An Array sub property


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


Solution

  • 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)
    }