Reputation: 165
Currently when I console.log(deckOfCards), it is returning all 52 cards, each with a suit, value, and points assigned to them.
{ suit: '♦', value: 'A', points: 11 }
{ suit: '♦', value: 2, points: 2 }
{ suit: '♦', value: 3, points: 3 }
.....
Now, I want to remove one card that has the suit, value and points from my deckOfCards array and return that.
{ suit: '♦', value: 'A', points: 11 }
This is to simulate dealing one card from the deck.
I have tried accessing each index of the array and adding them to the card variable, but it gave me an undefined for index 2.
For loops only return one array of suits and not the others.
I have changed the deckOfCards into an object that has the suit, value, and points in it.
My card constant is where I want to pull one card from the deck.
const suits = ["♦", "♣", "♥", "♠"];
const values = ["A", 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K"];
for (const suit of suits) {
for (const value of values) {
let points = parseInt(value);
if(value === "J" || value === "Q" || value === "K") points = 10;
if(value === "A") points = 11;
const deckOfCards = {suit, value, points};
const card = deckOfCards
}
}
EDIT TRYING TO ADD NEW METHOD
I'm trying to add two cards each to the player/dealer hands, but when i log it:
[ { suit: '♠', value: 'A', points: 11 } ]
[ { suit: '♠', value: 'A', points: 11 },
{ suit: '♦', value: 10, points: 10 } ]
Why am I getting 3 objects returned instead of 2?
const dealRandomCard = () => {
return deckOfCards.splice(Math.floor(Math.random() *
deckOfCards.length), 1)[0];
}
// console.log(dealRandomCard());
//////////////////////////////////////////////////////////////
for (let i = 0; i <= 1; i++) {
playerHand.push(dealRandomCard());
dealerHand.push(dealRandomCard());
console.log(playerHand);
// console.log(dealerHand);
}
Upvotes: 1
Views: 123
Reputation: 386550
You could use a single combined object to the result set. And an object for a shorter way of getting the points.
var suits = ["♦", "♣", "♥", "♠"],
values = ["A", 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K"],
cards = [],
suit,
value,
points = { A: 11, J: 10, Q: 10, K: 10 };
for (suit of suits) {
for (value of values) {
cards.push({ suit, value, points: points[value] || value });
}
}
function getCard() {
return cards.splice(Math.floor(Math.random() * cards.length), 1)[0];
}
console.log(getCard());
console.log(getCard());
console.log(getCard());
console.log(cards);
Upvotes: 2