I am working with an array that contains data about playing cards (cardInfo). Below is a snippet of the array in the code. Since there can be duplicates of each card, I aim to utilize this data to generate a deck by storing its information in a new array (drawPile) for every instance of that card type (indicated by the 'frequency1' property).
var common = 4;
var uncommon = 3;
var rare = 2;
var cardInfo = [
{name:'Card A',frequency1:common,frequency2:rare,frequency3:0},
{name:'Card B',frequency1:common,frequency2:uncommon,frequency3:0},
{name:'Card C',frequency1:uncommon,frequency2:uncommon,frequency3:0}
];
var drawPile = [];
for (var cType = 0; cType < cardInfo.length; cType++) {
for (var freq = 0; freq < cardInfo[cType].frequency1; freq++) {
drawPile.push(cardInfo[cType]);
console.log(drawPile.length - 1);
drawPile[(drawPile.length - 1)].id = (drawPile.length - 1);
console.log(drawPile[(drawPile.length - 1)]);
}
}
However, upon checking the console log, it appears that all 4 instances of "Card A" have the id property set to 3, all 4 of "Card B" have the id property as 7, and all 3 of "Card C" have the id as 10. It seems like the nested loop (freq) only executes after all the .push() commands, leading to repetitive ids.
Additionally, when implementing this script in jsfiddle, I can reproduce these results if I run it first and then view the console log. On the contrary, if I open the console log before running the code, it functions correctly.
How can I guarantee a unique identifier for each card?
EDIT: I encountered further peculiarity as I obtained identical outcomes even when incorporating a separate for loop exclusively for assigning the id property, demonstrated in this code.