Skip to content

JavaScript card game: set the player who deals the cards in each hand

I am working on a card game and I need to set the player who deals each hand.

I have two arrays, one stores the hands and the other stores the players.

hands = [
 {
   handNumber: 1,
   dealer: null
 },
 {
   handNumber: 2
   dealer: null
 }
 ...
]

players = ["Player 1", "Player 2", "Player 3", "Player 4"]

My goal is to assign a dealer to each hand in a consecutive way until reaching the max number of hands. For example:

Hand 1: Player 1
Hand 2: Player 2
Hand 3: Player 3
Hand 4: Player 4
Hand 5: Player 1
And so on

I tried different loops, but I am really stuck with this:

hands.forEach(hand => {
    for(let i = 0; i < players.length; i++) {
        hand.dealer = players[i]
    }
})

Any suggestions? Any help will be much appreciated.

Answer

You can use % in order to return back to never go out of range of the player’s array and always return to the start again:

For example: 0 % 3 == 0

1 % 3 == 1

2 % 3 == 2

3 % 3 == 0

4 % 3 == 1

hands.forEach((hand, index) => {
   hands[index] = players[index % players.length];
})

If you are interested you can read more about js operators here: https://www.w3schools.com/js/js_operators.asp