Home > Blockchain >  Placing an if statement within a map or forEach function
Placing an if statement within a map or forEach function

Time:12-19

✌️ Hi!

I am building a small word chain turns-based game with Node.js, Express & Socket.io. The players and their scores are displayed, refreshed at every turn, through this function:

function updatePlayersList(players) {
  const players_list = document.getElementById('players_list');
  players_list.innerHTML = players.map(player => `<li id="${player.id}">${player.name} - ${player.score}</li>`).join('');
}

Here's the players array:

[
  {
    id: 'opYbiuXzExmymRPvAAAV',
    name: 'Paul',
    score: 0,
    room: 'room',
    playing: true
},
{
    id: 'uvs4wxpZwsmaQ3G4AAAX',
    name: 'Ezio',
    score: 0,
    room: 'room',
    playing: true
  }
]

Which works fine and displays this. The player's whose turn it is gets his name with a border. Here's a game with only two players but more can play.

In this idea, I want to strike the name of the players who lost during the game. Their name still gets displayed so everyone knows who's still in and who's out, but they can't play anymore obviously, just keep watching.

So I was thinking an if statement inside the map function, adding a class .not-playing to the names of the players with playing: false (that's updated on the server side after each turn). But either way I am doing it wrong, or I have to use something else? Here's the modified code, but then no more players get displayed, neither the playing nor the not playing ones. Not what I want, obviously

  • Related