Including a property within a nested for-loop results in identical values being assigned to every parent for-loop

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.

Answer №1

While iterating through the cardInfo collection, each instance of cardInfo is being updated for every frequency looped over. It seems like the same instance of cardInfo is being modified repeatedly. You may think that using console.log in each iteration should display the correct output, but without debugging, it's uncertain whether this holds true during regular execution. How can you address this issue?

Realizing that the same instance was being modified with each frequency iteration, I decided to clone the card (albeit not the most efficient solution, but it proves a point). I accomplished this by using:

JSON.parse(JSON.stringify(cardInfo[cType]));

Although not the optimal method, it sheds light on where the problem might lie.

I have made this change in a sandbox environment (where I also simplified the code), and when you remove the cloning, it behaves as currently observed; however, with cloning, it functions as expected.

I hope this clarifies things for you.

Answer №2

When pushing object references to the drawPile array within a loop, all "Card A" cards end up with the same ID because they reference the same object. To avoid this issue, you need to clone the object before pushing it into the array. Below is a suggested change for your code:


for (var freq = 0; freq < cardInfo[cType].frequency1; freq++) {
    drawPile.push(JSON.parse(JSON.stringify(cardInfo[cType])));
    console.log(drawPile.length - 1);
    drawPile[(drawPile.length - 1)].id = (drawPile.length - 1);
    console.log(drawPile[(drawPile.length - 1)]);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Executing an SQL delete query with a button click using a JavaScript function in PHP

I have created a setup with three essential files - index.html, database.php, and function.js. In database.php, there is a form generated containing a delete button that triggers the deletion SQL query when clicked. The primary objective is to present a ta ...

"Failure encountered when attempting to update a dictionary using a specific key, despite the key

This situation is quite confusing I am working with multiple dictionaries of data in an attempt to create a new one. While looping through the data and checking for keys, I have encountered a strange issue. If completeDictionary.ContainsKey(sale("splitT ...

What steps should be taken to make mocha utilize the HTTP response?

Every time I make an http call, the function it returns causes my comparison to fail because [Function] is never equal to the value I want. Is there a way to make my assert statement consider the true/false flag within it? # test/helloWorld.js const othe ...

When I try to pass a variable as a prop to another .js file, it mysteriously transforms into an undefined value

Upon successful login, my app file sets the isAuthenticated variable to true and redirects to the /admin page. The Firebase API call is functioning as expected, allowing access only with a valid username and password. The issue arises when I try to hide t ...

Using the goBack function in React Router does not add the previous location to the stack

In React Router v4, I have a list page and a details page in my web application. I want to implement a 'Save and close' button on the details page that redirects the user back to the list page when clicked. However, I noticed that after the user ...

Why does a React error keep popping up when trying to set a background-image in my CSS?

I've been working on my React project and I can't figure out why I keep encountering this error. I double-checked the URL paths and made sure they were named correctly, yet the error persists. Here is a snippet of my CSS: background-image: url ...

Is it possible to employ JavaScript for performing a Ctrl-F5 refresh?

I'm working with a small asp file that runs in a frame. Is there a way to trigger a CTRL+F5 type of refresh to reload the entire browser window? I've attempted using parent.location.reload(true), location.reload(), and various other methods, but ...

Empty Media Viewer

I am encountering an issue with setting up a code, as it only displays a blank white page. Any suggestions on what might be causing this problem in the setup and assistance in resolving it would be greatly appreciated. <script type="text/javascript ...

Model of Objects within a Document

Here's a puzzling question for you: why does console.log(document.body) and console.log(document.head) work perfectly fine, but console.log(document.script) or console.log(document.html) don't seem to do anything? It's strange because all of ...

Avoid directing to the identical component within a React application

When I try to redirect my component to the same component with different parameters, it is not working properly. <BrowserRouter basename={process.env.REACT_APP_DEFAULT_PATH ?? ''}> <Switch> ... < ...

Transmitting FormData from Angular to a .NET MVC Controller

Here's my perspective: <form ng-submit="onFormSubmit()"> <div class="form-group"> <label for="Movie_Genre">Genre</label> @Html.DropDownListFor(m => m.Movie.GenreId, new SelectList(Model.Genres, "Id", "Na ...

Enhance the speed of AJAX search within a UL LI list containing over 5000 objects

Dear Stack community, I've been working on a simple Ajax js search using .addClass and .removeClass as I discovered it's faster than using .show() and .hide(). However, the speed is still not up to par and I'm feeling quite lost. You can ...

Invoke the javascript function by referencing the JavaScript file

I'm encountering an issue with two JavaScript files. One file uses the prototype syntax, while the other utilizes jQuery. Unfortunately, they don't seem to work harmoniously together. I've attempted calling the functions within the files usi ...

Facing an issue where the CSS class name is not displaying correctly when utilizing CSS Modules with my React

This webpack.config.js file is dedicated to the module section, where loaders are defined for JSX files and CSS. module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'bab ...

JSON function invocation is failing to load

This is my JavaScript script, When I call the function calculate(), the JSON method ConvertDataTabletoString() only gets called once, when I load the page. I want the method to be called every 5 seconds. I am calling a VB.NET function in .aspx. How can ...

In JavaScript, eliminate all characters in a string after the second hyphen using only one line of code

Is it possible to extract the language from a string before the 2nd occurrence of a dash (-) using a single line of Javascript? For example: en-AU-Option-A would become en-AU ...

Launch a new pop-up window with a specific size to display the form

I need to implement functionality for a Submit button on my new form that passes parameters to another page and opens a new pop-up window sized to specific dimensions. I already have this working with a hyperlink, but now I need the same functionality fo ...

Using Typescript: Defining a function parameter that can be either of two interfaces

While browsing through this specific question, I noticed that it was somewhat related to my current issue, although there were notable differences. In my scenario, I have a function named parseScanResults which accepts an object as its argument. This obje ...

retrieve data from a multidimensional array

I am working with an array: array(5) { [0]=> array(2) { [0]=> string(5) "REFER" [1]=> string(12) "Não Sócios" } [1]=> array(2) { [0]=> string(5) "REFER" [1]=> string(12) "Não Sócios" } [2]=> array(2) { [0]=> str ...

organizing data using backbone marionette router

I am attempting to display the query string, but I am only receiving null as output. The query string I am using is http:://localhost/admin/brands?foo=bar and no matter what I try, queryString remains null. I even attempted /brands/?foo=bar with no succes ...