Looping through multi-dimensional arrays in JavaScript is a necessary task for accessing

I have been trying to figure out how to create a multidimensional array like this: [[A1, B1, C1....],[A2, B2, C2....]];

let grid = [
  []
];
let letters = "abcdefghij".toUpperCase();

// Generating the Grid
const generateGrid = (size) => {
  let row = 0;
  let col = 0;
  for (row = 0; row < size; row++) {
    grid[row] = [];
    for (col = 0; col < letters.length; col++) {
      grid[row][col] = `${letters[row]}${col + 1}`;
    }
  }
};

generateGrid(letters.length);
console.log(grid);

Answer №1

If you're open to upgrading your code to ES6 and beyond, this solution should work for you.

const alphabet = "abcdefghij".toUpperCase();

const generateGrid = (alphabet) => Array.from(
    { length: alphabet.length },
    (_, index) => [...alphabet].map((letter) => `${letter}${index + 1}`)
);

console.log(generateGrid(alphabet));

Answer №2

Make sure to reference the col instead of the row and combine the value of row + 1 to it within the inner loop while assigning.

let grid = [
  []
];
let letters = "abcdefghij".toUpperCase();

// Generating the Grid
const generateGrid = (size) => {
  let row = 0;
  let col = 0;
  for (row = 0; row < size; row++) {
    grid[row] = [];
    for (col = 0; col < letters.length; col++) {
      // Replace grid[row][col] = `${letters[row]}${col + 1}` with
      grid[row][col] = `${letters[col]}${row + 1}`;
    }
  }
};

generateGrid(letters.length);
console.log(grid);

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

Error encountered during the conversion process from Collection to array: ClassCastException

I'm currently working on a project where I need to convert a given Collection into an array. Here is the code I have so far: public class InsertionSorter< T extends Comparable<T>> { private T[] array; @SuppressWarnings("unchecke ...

Issue encountered with the malloc function in C

For my exercise, I am tasked with initializing space from the heap in function1() and creating an array there. In the main function, I should print the array. Can you help me identify what I did incorrectly? CODE #include <stdio.h> #include <st ...

Rendering React Js component occurs just once following a state update

My journey with ReactJS is just beginning, and I'm facing an unusual issue which might be due to my unconventional implementation approach. Previously, everything was working smoothly. However, when I tried to introduce new features, things started g ...

Error: Attempted to update user profile with an invalid function in Firebase

After creating an Avatar Chooser, I am encountering an error when selecting an image. Instead of displaying the selected image in the avatar, the error message is being displayed. How can I resolve this and ensure that the image appears in the Avatar Icon ...

Limit the jQuery dialogue button to just one click

My goal is to create a jQuery dialogue box that sends data when the 'OK' button is clicked. The challenge I'm facing is making sure it only sends the data once, regardless of how many times the button is clicked. $.dialogue({ ...

A guide on setting up fixed row numbers in MUI-X DataGrid

One challenge I am facing is rendering the row numbers in a table so that they remain static even when columns are sorted or filtered. I attempted to use the getRowIndexRelativeToVisibleRows method of the grid API, but unfortunately, it does not work as ex ...

Acquire the model from a field within an Angular Formly wrapper

I'm in the process of designing a wrapper that will exhibit the model value as regular text on the page. Once the mouse hovers over this text, it transforms into a Formly field, which works perfectly fine. However, I'm encountering an issue where ...

Is it possible to arrange JSON Objects vertically on a webpage using tables, flexboxes, divs, and Javascript?

Within my JSON data, I have multiple products defined. My goal is to loop through this JSON and display these products side by side on a web page for easy comparison. Initially, I envision structuring them in columns and then rows: https://i.sstatic.net/K ...

Challenges with browsing navigation in Selenium WebDriver

Recently, I began my journey of learning selenium WebDriver. In an attempt to automate the task of logging into an account using the Firefox browser, I encountered a discrepancy. Manually opening the browser and clicking on the login link from the homepag ...

Create dynamic HTML files using Express, EJS, and FS, and deliver them using Nginx as the server instead of relying

Imagine a scenario where we have a JSON object: [ { "id": 1, "title": "Title 1", "description": "Description 1" }, { "id": 2, "title": "Title 2", ...

Updating class with jQuery based on dynamically changing content

I am using countdown.js to create a custom countdown timer. My goal is to replicate the countdown timer seen on the homepage, but with the ability to change the target date (which I have already accomplished). Here is an example of what I currently have f ...

Issues with AngularJS Validation not functioning properly with File Inputs marked as 'Required'

I've been experimenting with this issue and haven't been able to solve it. While creating an Angular form, I found that validation works fine when the required attribute is used in a text field. However, when I tried adding a file input type with ...

Is it possible to create a React Component without using a Function or Class

At times, I've come across and written React code that looks like this: const text = ( <p> Some text </p> ); While this method does work, are there any potential issues with it? I understand that I can't use props in this s ...

Is it possible for me to access information from an external URL using JSON?

As I delve into learning about JSON for app development, I've encountered an issue with a JSON and PHP-based chat system. While the code functions properly for the same origin policy, when it comes to sending and receiving data from an external URL, i ...

Passing props to component elements through slots in Vue.js

Trying to pass props from a component element that includes a slot PatientBooking.vue <user-profile :titlename="BOOKINGDETAIL"> <div class="block"> <div>Ereferral: 84884jjd</div> <div>Gender: Mal ...

What is the best way to select an element based on its relationship to another Element object using a selector?

I am currently developing a small library in which I require the ability to select a relative element to the targeted element using the querySelector method. For instance: HTML <div class="target"></div> <div class="relative"></div& ...

When the icon is clicked, the text goes over the ul and the mobile slide menu goes beneath it

click here for the image Is there a way to make the text move below when I click on the hamburger menu icon? ...

What is the method to show text exclusively upon hovering the mouse?

Here is a sample that I'm working with: link HTML CODE: SED PERSPICIATIS Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore ...

Constructing a regular expression

I've been exploring JavaScript regular expressions and encountering some challenges while trying to build a larger one. Therefore, I have decided to seek help for the entire problem rather than just individual questions. What I am looking for is a re ...

Create a custom slider using jQuery that pulls in real-time data for a dynamic user

My goal is to implement a dynamic slider feature in my Django project by using jQuery and ajax. I have managed to create previous and next buttons for swiping through profiles with the help of others, but I am currently facing an issue with a NoReverseMatc ...