Troubles encountered with basic nested for loops in Javascript

I encountered a unique issue while working with nested for loops in Javascript. My goal was to populate an array of answers in one language and then include those in another array. However, I noticed that only the last iteration of the inner for loop's array was being used in the output. After researching, I suspect it may be related to closures, but since there are no multiple functions involved, I am unsure how to address this issue. Here is a link to the JS Fiddle showing the problem.

Below is the code snippet:

var answer_array = [];
var content_array = [];
var i18n_array = ['en', 'fr', 'es'];

for (var i18nCount = 0; i18nCount < 3; i18nCount++) {

    var i18nLang = i18n_array[i18nCount];

        for (var ansIndex = 0; ansIndex < 3; ansIndex++) {
            answer_array[ansIndex] = {
                value: 'This is answer # ' + ansIndex + ' in this language ' + i18nLang
            };
        }

        console.log(i18nCount);
        console.log(i18nLang);
        console.log(JSON.stringify(answer_array,null,4));

    content_array[i18nCount] = {
        i18n: i18nLang,
        text: 'This question is in ' + i18nLang + ' language?',
        answers: answer_array,
    };
}

console.log(JSON.stringify(content_array,null,4));

The produced output showcases this unexpected behavior:

    0
en
[
    {
        "value": "This is answer # 0 in this language en"
    },
    {
        "value": "This is answer # 1 in this language en"
    },
    {
        "value": "This is answer # 2 in this language en"
    }
]
1
fr
[
    {
        "value": "This is answer # 0 in this language fr"
    },
    {
        "value": "This is answer # 1 in this language fr"
    },
    {
        "value": "This is answer # 2 in this language fr"
    }
]
2
es
[
    {
        "value": "This is answer # 0 in this language es"
    },
    {
        "value": "This is answer # 1 in this language es"
    },
    {
        "value": "This is answer # 2 in this language es"
    }
]
[
    {
        "i18n": "en",
        "text": "This question is in en language?",
        "answers": [
            {
                "value": "This is answer # 0 in this language es"
            },
            {
                "value": "This is answer # 1 in this language es"
            },
            {
                "value": "This is answer # 2 in this language es"
            }
        ]
    },
    {
        "i18n": "fr",
        "text": "This question is in fr language?",
        "answers": [
            {
                "value": "This is answer # 0 in this language es"
            },
            {
                "value": "This is answer # 1 in this language es"
            },
            {
                "value": "This is answer # 2 in this language es"
            }
        ]
    },
    {
        "i18n": "es",
        "text": "This question is in es language?",
        "answers": [
            {
                "value": "This is answer # 0 in this language es"
            },
            {
                "value": "This is answer # 1 in this language es"
            },
            {
                "value": "This is answer # 2 in this language es"
            }
        ]
    }
]

Answer №1

You have been repeatedly using the same answer_array, constantly overwriting its 3 members.

Instead of declaring it outside the loop, consider creating a new array at each iteration of the external loop.

Here's an example:

var content_array = [];
var i18n_array = ['en', 'fr', 'es'];

for (var i18nCount = 0; i18nCount < 3; i18nCount++) {
    var answer_array = []; // Ensure to move this declaration inside
    var i18nLang = i18n_array[i18nCount];

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

The process of establishing this navigation bar at the top of the slider

https://i.sstatic.net/Hyv5R.jpg Could someone please provide me with the CSS and HTML code for this? https://www.mi.com/en/ This is the website link where I am trying to replicate the navigation bar, but I am struggling to understand how the navigation ...

Can someone provide instructions on how to convert base64 data to an image file

I'm utilizing the vue-signature Library but I am unsure how to download the base64 data that is generated as an image. Here is the link to the library: https://www.npmjs.com/package/vue-signature. I have gone through the documentation and noticed that ...

Accessing information from a db.json file and populating an array with it through the use of JavaScript

Within my game project, I have implemented ajax and javascript to interact with a server created through json-server. This server houses a db.json file containing various words that users can input and utilize within the game. db.json Structure This is t ...

What is the best way to include several lines between code blocks using Prettier?

After implementing Prettier into my coding workflow, I encountered an issue where it lacks the ability to adjust the number of blank lines between code blocks. By default, it only includes one blank line. I am in need of 2 blank lines: const bar = 10; // ...

Displaying a meager 0.5% on the BootStrap progress indicator

Utilizing the bootstrap progress bar to display the percentage of a person's miles covered out of a total of 23,872 miles. Take user A as an example, they have covered only 5 miles: 5/23872 = 0.00020945 * 100 = 0.02094504 miles. Currently, anything ...

Issue with data retrieval from Firebase snapshot reference

While working with Firebase, I encountered an issue related to setting and getting priorities of items in a list of people. Surprisingly, the functionality seems to work fine in one function but throws an error in another. When trying to get the priority ...

Utilizing jQuery to create a blocking modal with a spinning gif, without the need for jQuery Block

When working on a Bootstrap page and faced with a time-consuming task, it's common to want a spinning GIF to show that the process is happening and to prevent users from interacting with certain parts of the UI. While jQuery offers the plugin jQuery ...

Tips for incorporating reflection in Vue.js?

In my current scenario, I am receiving a message from SignalR and attempting to create an object based on the name included in the message. Previously, I encountered a similar situation in AngularJS where we addressed it by utilizing an $injector with the ...

Error: The function $(...) that is being called is not recognized as a dialog function

My website has been giving me headaches as I try to integrate a basic CMS. Despite three full days of work, I am still facing one persistent problem! I have exhausted all my known methods, researched some solutions, but none seem to work. In order to iden ...

What is the best way to update just the image path in the source using jQuery?

I am currently working on implementing a dark mode function for my website, and I have successfully adjusted the divs and other elements. However, I am facing an issue with changing the paths of images. In order to enable dark mode, I have created two sep ...

There is an issue with the hook call while trying to establish a context with a reducer

I am facing an issue while setting up the AppProvider component that utilizes a context and reducer to manage global data for my application. The problem seems to be arising from the useReducer hook used within the AppProvider. I have checked the error mes ...

What are the steps to create a unique popup div effect with jQuery?

Upon clicking the icon on this page, a mysterious div appears with information. I'm completely baffled by how they achieved this cool effect using css/jQuery tools. Can anyone shed some light on the mechanism behind this? ...

Is there a method to ensure that the window event always gets triggered before any other events?

Is there a way to make the window event trigger first when clicking on #myDiv? (function ($, w, d) { $(d).ready(function () { $(w).click(function() { alert('window has been clicked'); }); $('#myDiv').cl ...

why doesn't the promise return the record after it has been updated

After completing the form, I proceed to send it as an object to the API NodeJS. The following is the execution function: .post('/create/card', function (req, res) { var rb = req.body, obj = { query: { $set ...

Eliminate items from a list that have duplicate properties

I have a collection of objects, each with a unique NAME property. However, there are duplicates in the collection where some objects share the same NAME. const arr = [ {name: "x", place: "a", age: "13" }, {name: "x", place: "b", age: "14" }, { ...

The componentWillUnmount method is not being called

I'm currently working on a Backbone application and I'm in the process of integrating React components. The React component is being mounted using the following code: ReactDOM.render( <WrappedComponent />, node ); where "node" represents ...

Display a helpful tooltip when hovering over elements with the use of d3-tip.js

Is it possible to display a tooltip when hovering over existing SVG elements? In this example, the elements are created during data binding. However, in my case, the circles already exist in the DOM and I need to select them right after selectedElms.enter ...

"Enhance your website with autocomplete feature using the power of jQuery 1.4.2 and jQuery UI 1

Struggling to make jQuery autocomplete work. Despite searching for examples, most seem outdated. Modeled after a good example from the jQuery UI site but still can't get it to display data. My JSON data source is accessed via URL. [{ "pk": 1, "mo ...

Chartjs-node in conjunction with prebuilt canvas is persistently generating 'Cairo not detected' errors

Currently, I am utilizing chartjs-node for creating charts. On my local (Windows) machine, the node.js code works flawlessly, likely due to having windows-build-tools with the cairo package installed. However, when attempting to compile on my remote (Linu ...

Having trouble retrieving the component state within AgGrid's cellRenderer

When working on my React app using functional components, I encountered an issue with accessing a local state (myObj) within a cellRenderer in AgGrid. The local state is populated via a context object from the parent component based on an API response. Un ...