Reputation: 61
I am creating a card game. I am trying to loop two arrays. I am able to do it with a for
loop, but I want to use forEach()
. I am not getting the right results. Below is the for loop that works, and then the forEach()
way I've tried:
const suits = ['Heart','Diamond','Spade','Club']
const values=['2','3','4','5','6','7','8','9','K','Q','J','A']
const deck = []
for(i = 0; i<values.length; i++){
for(x =0; x < suits.length; x++){
const card = {value: values[i], suits: suits[x]}
deck.push(card)
}
}
values.forEach((value,x) => {
suits.forEach((suit,i) => {
const card = {value: value[x], suits: suit[i]}
deck.push(card)
})
})
Upvotes: 0
Views: 136
Reputation: 450
In each iteration your arguments of forEach callbacks are ready to use in card object.
values.forEach(value => {
suits.forEach(suit => {
const card = { value, suits }
deck.push(card)
})
})
Upvotes: 0
Reputation: 50797
Perhaps nicer than either a for
loop or a forEach
one is to use a technique designed to change one array into another, index by index, such as map
or flatMap
.
Here, creating the deck might be a one-liner:
const suits = ['Heart','Diamond','Spade','Club']
const vals = ['2','3','4','5','6','7','8','9','K','Q','J','A']
const deck = vals .flatMap (value => suits .map (suit => ({value, suit}) ))
console .log (
deck
)
Also note that there is a fairly strong tradition, at least in the U.S., of ordering the suits from low to high as "clubs, diamonds, hearts, spades". In English this is easy to remember as they are sorted alphabetically.
Upvotes: 1
Reputation: 5940
You don't need i
or x
as value
, suit
have the values of each array
const suits = ['Heart','Diamond','Spade','Club']
const values=['2','3','4','5','6','7','8','9','K','Q','J','A']
const deck = []
values.forEach((value) => {
suits.forEach((suit) => {
const card = {value: value, suits: suit}
deck.push(card)
document.getElementById("content").innerHTML += JSON.stringify(card) + "<br />"
})
})
<span id="content"></span>
Upvotes: 0
Reputation: 281726
With your forEach
you need not use index to access the value, you simply get the value from the argument for callback. However if you are using index, you need to access values[x], suits[i]
instead of value[x], suit[i]
.
const suits = ['Heart','Diamond','Spade','Club']
const values=['2','3','4','5','6','7','8','9','K','Q','J','A']
const deck = [];
values.forEach((value,x) => {
suits.forEach((suit,i) => {
const card = {value: value, suits: suit}
deck.push(card)
})
})
console.log(deck)
Upvotes: 3