Shuffling a Deck of Cards with JavaScript
In developing a recent front-end application using Vanilla JavaScript (Rock Paper Scissors: War) I found an excellent solution to a problem when I discovered the Fisher Yates algorithm. I was searching for the best way on how to truly shuffle a deck of cards using JavaScript.
This algorithm truly randomizes a deck of cards in an array, allowing for a unique gameplay. It worked well for the purposes I was using it.
So, my challenge was to take a deck of cards and to shuffle them, allowing for a completely randomized gameplay experience. Ultimately, I came across the Fisher Yates algorithm and was able to solve the challenge with ease.
The Shuffle Deck Function
function shuffleDeck(array) {
currentCard = 0;
for(let i = array.length - 1; i > 0; i--){
const j = Math.floor(Math.random() * (i + 1));
const temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
The above code takes an array as an argument and randomizes every index within that array. This means that each card in the array is taken from its initial position and moved into a random position within the same array. Exactly like if one were to shuffle, say, a deck of cards.
See it in action
See this cool function in action here on my site. Also, do feel welcome to check out my github repository for this fun project.
Finally, I hope this short post can help just a little bit if you’re trying to truly randomize/shuffle a deck of cards using JavaScript.
Recent Comments