Having difficulty populating a bidimensional array with objects in JavaScript

I have an array positioned "globally" (outside of any function in my document).

var arrayBidimensional;

Next, I am attempting to fill it like this:

var objectLetter = new objectLetter("","","","","");    

arrayBidimensional = new Array(size);

for (i = 0; i < size; i++)
    arrayBidimensional[i] = new Array(size);

var random = Math.floor((Math.random()*26) + 0); 

for (var i = size - 1; i >= 0; i--) 
{
    for (var j = size - 1; j >= 0; j--) 
    {
        random = Math.floor((Math.random()*26) + 0);
        objectLetter.letter = letters[random];
        objectLetter.letterPosX = j;
        objectLetter.letterPosY = i;
        objectLetter.wordShape = "no";
        objectLetter.identifier = j + "" + i;
        arrayBidimensional[i][j] = objectLetter;            
    }

}  

However, when I try to access this array at a specific position like array[X][X]

all I get is the value from the very first position. For example, if the first position (0,0) is "A", then the entire array displays "A" at every position, even [(max position), (max position)].

How do I know this? Well, I am constructing a table with td elements like this:

'<td width="30">' + arrayBidimensional[i][j].letter + '</td>'

Consequently, the entire table just shows "A" in every cell... So... What am I doing wrong?

Your assistance on this matter is greatly appreciated! Thank you.

Answer №1

To populate the array with objects representing each location, you must create a new instance of objectLetter for every position:

arrayBidimensional = new Array(size);

for (let i = 0; i < size; i++) {
    arrayBidimensional[i] = new Array(size);
}

for (let i = size - 1; i >= 0; i--) 
{
    for (let j = size - 1; j >= 0; j--) 
    {
        let letterObject = new objectLetter("","","","","");
        let randomIndex = Math.floor((Math.random()*26) + 0);

        letterObject.letter = letters[randomIndex];
        letterObject.posX = j;
        letterObject.posY = i;
        letterObject.wordShape = "no";
        letterObject.id = j + "" + i;
        arrayBidimensional[i][j] = letterObject;            
    }
}  

Answer №2

Check out this example of a Multidimensional Array in JavaScript:

var multiArray = [['Apple', 5, 'Orange'],['Banana', 10, 'Grapes']];

Alternatively, you can also create it like this:

var multiArray = new Array(new Array('Apple', 5, 'Orange'), new Array('Banana', 10, 'Grapes'));

console.log(multiArray[1][2]); // 'Grapes'
console.log(multiArray[0][1]); // 5

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

What is the best way to assign a unique background color to each individual card in my card list?

I have a list of cards and I want to assign a unique color to each card in the list. I attempted to do this on my own, but it ended up being more complex than I anticipated. Here is the list of cards: return ( <Container> <Row className=&qu ...

Real-time chart updates through REST API integration with JavaScript

I am searching for a JavaScript library that is capable of creating line charts and making calls to a REST API every few seconds (such as 5s or 3s) in order to update the line chart dynamically. I have found some libraries that support live chart updatin ...

Observer function simulated by SinonStub

I am currently testing express middleware using sinon.js My goal is to verify that it sends a specific JSON response and prevents the request from moving on to the next middleware or request handler. const middleware = (req: Request, res: Response, nex ...

What is the method for configuring Express to serve static files from a parent directory?

If I have a nodejs express application with the following folder structure: -app - frontend - assets - images - scripts - styles - ... - pages - backend - server.js How can I serve the static files in the assets fold ...

Differences in characteristics of Javascript and Python

As I tackle an exam question involving the calculation of delta for put and call options using the Black and Scholes formula, I stumbled upon a helpful website . Upon inspecting their code, I discovered this specific function: getDelta: function(spot, str ...

Hidden visibility of input field prevents the value from being posted

I have a dropdown menu containing numbers as options. When a user selects a number, I want to display an input box using jQuery based on their selection. However, the issue arises when I try to submit the values of these input boxes as they are not being s ...

Which one should I use: ng-repeat or ng-options?

I am looking to display JSON data in a dropdown list, and I have two options to choose from. The first option is using ng-repeat, while the other option is ng-options. Using ng-repeat: In the HTML file: <select> <option ng-repeat="prod in testA ...

Changing the variable within a promise in Angular 1

There seems to be an issue with updating a variable within the callback function of a promise, as shown in the code snippet below: $scope.showSelected= function (node){ var promise = $http.get("http://127.0.0.1:5000/getResource?ldpr="+nod ...

Issues arise with routing when specific route parameters are implemented

After setting a route parameter in my browser URL, I encountered errors with the routing of the public folder (which contains my CSS, JS, etc.). The app's structure is as follows: app | |-- public | └-- css | └-- profile.css | |-- ...

What is the best way to fetch JSON data in React from the start and then manipulate it as needed before exporting to another file within my application?

I have a scenario where I need to fetch data from a MongoDB database using async/await fetch() and save it in a file called data.js. However, I am facing an issue with React executing "in parallel" due to the nature of async/await. This makes it difficult ...

SyntaxError: VM3419:1 - Unexpected token "<" was not caught

I'm exploring AJAX techniques in a demo project where I retrieve data from the server using AJAX methods. However, I encountered the following error: " Uncaught SyntaxError: Unexpected token< xhr.onreadystatechange @main.js" JS: (function ...

Tips for inserting information from a JSON file into a mailto hyperlink

As a newcomer to JavaScript, I am eager to tackle the challenge presented below: Situation: In possession of a JSON file containing personal details such as name, email address, bio, etc., my task is to design a basic web page showcasing this data for ea ...

Ways to substitute the $(document).ready function?

I'm facing a problem and struggling to find a solution. Here is the JavaScript script that's causing me trouble: $(function () { $.ajaxSetup({ cache: false }); var timer = window.setTimeout(function () { $(".alert").fadeTo(10 ...

What is the best way to navigate to a new webpage after clicking a button?

Currently, I am experimenting with socket io and node to show two different HTML pages. Here's what I have set up: app.get("/", function(req, res) { res.sendFile(__dirname + "/login.html") }) The scenario involves a user logging in and pressing ...

Unable to retrieve the iframe variable from the parent as it returns undefined

I am trying to retrieve a variable within an iframe from the parent index.html. Here is the index.html code: <!doctype html> <html lang="en-us> <head> <title>Test</title> </head> <body> <p>Test& ...

Using jQuery to swap out sections of a HTML tag

Similar Question: Use of jQuery for Modifying an HTML Tag? After extensive research, I have not come across a solution that fits my specific requirements. My objective is to replace a part of an HTML tag without completely replacing the entire tag. To ...

Navigating errors during the distribution of numerous messages with SendGrid and Node.js

I have developed a command line application that interacts with a DynamoDB table to extract email addresses for items that have not yet received an email. The process involves creating customized message objects, sending emails using SendGrid's sgMail ...

Encountering a type error when attempting to assign an interface to a property

In my Angular project, I am working with typescript and trying to assign the IInfoPage interface to some data. export interface IInfoPage { href: string; icon: string; routing: boolean; order: number; styleType: string; ...

Using Vanilla JavaScript to Disable a Specific Key Combination on a Web Page

On a completely random English-Wikipedia editing page, there exists a way to add content (for example, "test") and save it using the existing key combination of Alt+Shift+S. My goal is to specifically prevent this action without removing the save button b ...

Running the JavaScript function prior to its interval being triggered

I'm in the process of developing a PHP dashboard page with various features, but there's one particular issue that bothers me, although it's not too major. The problem I'm facing is that I have a JavaScript function that fetches data a ...