Creating a 2D array matrix in JavaScript using a for loop and seamlessly continuing the number count onto the next row

I'm attempting to create a 2d matrix with numbers that continue onto the next row.

var myMatrix = [];

var rows = 5;
var columns = 3;

for (var i = 0; i < rows; i++) {
  var temp = 1;
  myMatrix[i] = [i];
  for (var j = 0; j < columns; j++) {
    myMatrix[i][j] = [i + j];
  }

}

console.log(myMatrix);

I want it to display numbers like this:

123

456

789 and so on...

but I am struggling to achieve that:/

Could someone provide assistance and also recommend a video or website with examples where I can learn more about this type of topic?

Answer №1

Let's take a closer look at the functionality of your code:

const myMatrix = [];
const rows = 5;
const columns = 3;

for (var i = 0; i < rows; i++) {
  myMatrix[i] = [i];
  for (var j = 0; j < columns; j++) {    
    myMatrix[i][j] = [i+j];
  }
}

console.log(myMatrix);

You may have inadvertently made a typo in your row/ rows variable name. Setting that aside...

Your line myMatrix[i] is producing an array at position i, which is then assigned to an array with the value of i. This results in a strange combination where each "row" receives an array with its row number as the first value, something like this:

[[0], [1], [2], [3], [4]]

Subsequently, your inner loop appends a value to that array and sums up i+j, but encloses it within an array, when that is not the desired outcome. Consequently, you end up with something along these lines:

[
 [[0], [1], [2]], // i = 0
 [[1], [2], [3]], // i = 1
 [[2], [3], [4]], // i = 2
 // ... etc
]

Furthermore, note that you are overwriting that initial [i] anyhow, so it would be more appropriate to initialize it as an empty array [].

The intended result should resemble the following structure:

const myMatrix = [];
const rows = 5;
const columns = 3;

for (var i = 0; i < rows; i++) {
  myMatrix[i] = [];
  for (var j = 0; j < columns; j++) {    
    myMatrix[i][j] = (i*columns)+j;
  }
}

console.log(myMatrix);

Three modifications were made to your original code:

  • Adjust [i] to simply [], while maintaining consistency.
  • Omit the array encapsulation from the i+j calculation, aiming solely for a value.
  • When adding i, multiply by columns to prevent resetting every iteration: (i*columns)+j

This amended script will yield a clean output, initiated from 0. To commence from 1, consider incrementing your value by one:

const myMatrix = [];
const rows = 5;
const columns = 3;

for (var i = 0; i < rows; i++) {
  myMatrix[i] = [];
  for (var j = 0; j < columns; j++) {    
    myMatrix[i][j] = (i*columns)+j+1;
  }
}

console.log(myMatrix);

Answer №2

To calculate the position, use the formula i multiplied by columns plus j ... additionally, 30 characters need to be added for padding

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 transform a plain array without any Parent IDs into a tree structure in PHP?

I am currently working with a complex array structure that looks like this: Grandfather's name | Father's name | Son's name JOHN | RAY | TERRENCE JOHN | TIM | MICHAEL JOHN | TIM | RYAN BILL | SAM | HANK BILL | SAM | WILL BILL | LEO | DONALD ...

What is the best way to neatly import multiple images in Next.js?

I have a dilemma involving 10 images located in my public directory that I need to use in a component. Instead of individually importing each image like this: import imgurl1 from "../../public/celsius.gif"; import imgurl2 from "../../public/ ...

Customizing the jQuery Datepicker to only allow a predefined set of dates

I am looking for assistance regarding the jQuery datepicker. I have an array of dates and I need to disable all dates except for the ones in this specific array. Currently, the code I have does the opposite of what I need. I generate the array of dates in ...

Understanding ReactJS's process of batching all DOM updates within a single event loop, ultimately minimizing the number of repaints needed

While perusing an article on DOM updates in ReactJS, I came across the concept of React updating all changes within a single event loop. Having a background in understanding event loops in JavaScript and how they function in core JavaScript, I am curious ...

Ways to effectively store continuous scale data in a database

I am currently running a straightforward Node.js server (using Express) on my local machine on port 8000. By utilizing the npm package serialport, I have successfully connected to a scale and am able to retrieve its weight in a continuous manner as shown ...

NG build error: Module parsing failed due to an unexpected token - no updates made

Two days ago, out of nowhere, we started encountering build errors during deployment using GitLab CI. No alterations have been made to the build scripts, and none of the versions of NPM, NG, or Angular have been modified. The same compilation commands cont ...

Issue with Ant Design form validation

After reading through the documentation, I attempted to implement the code provided: Here is a basic example: import { Button, Form, Input } from "antd"; export default function App() { const [form] = Form.useForm(); return ( <Form f ...

Tips for styling the output of var_dump with an array

I currently have a script that retrieves an array from an API URL. <?php $url = 'https://api.example.com/v1/w'; $data = file_get_contents($url); $data = json ...

Title: "Customizing Labels on Stack Bars and Lines in D3.js Visualization"

Currently working on a stacked bar chart with a line chart on dual axis using D3.js and facing difficulty aligning labels correctly. Check out the code I have experimented with so far: https://plnkr.co/edit/doobXBC5hgzvGwDLvArF?p=preview I am looking to ...

Updating Cart Array in Angular 4 when Adding a New Item

I'm currently using angular 4 and I have encountered an issue in the code where adding a new product to the cart overwrites the existing item instead of appending it to the array. Here is a screenshot illustrating the problem cart.service.ts export ...

Troubleshooting server-side sorting issues with AJAX implementation, encountering problems with headers functionality

I'm encountering a problem: Some headers are not functioning properly to sort the table. For example, Brand and Model work as expected, but VehicleType only works once, and CarID and ReleaseDate never seem to work. Here is my index.php file: index. ...

The issue of resolving NestJs ParseEnumPipe

I'm currently using the NestJs framework (which I absolutely adore) and I need to validate incoming data against an Enum in Typscript. Here's what I have: enum ProductAction { PURCHASE = 'PURCHASE', } @Patch('products/:uuid&apos ...

When CSS is modified by inserting an extra div, it causes the positioning of other elements to shift towards

I'm currently working on adapting a method to make elements "sticky" for older browsers as discussed in this particular article. The basic idea involves implementing some JavaScript code that listens for scroll events. Upon detection of such an event ...

You are able to use a null type as an index in angular.ts(2538) error message occurred

onClick() { let obj = { fName: "ali", LName: "sarabi", age: "19", } let fieldName = prompt("field"); alert(obj[fieldName]); } I encountered an issue with the code above where alert(obj[fieldName] ...

What is the best way to convert an object array into an array with identifiers for duplicate values?

Working with the following array of objects: const data = [ {count: 400, value: "Car Wash Drops"}, {count: 48, value: "Personal/Seeding"}, {count: 48, value: "Personal/Seeding"}, ]; I want to use the map function to create an array with an addition ...

Developing modular applications with Vue.js and leveraging locally installed NPM packages

I am currently working on developing a modular application using Vue through the vue-cli-service. The main application and its modules are located in separate folders, with a structure that looks something like this: -- app/package.json /src/** -- mo ...

Angular's route resolve feature does not wait for the promise to resolve before

I just started using angular and I'm facing an issue with my user route. I'm trying to resolve the user object before rendering the view, but even after injecting $q and deferring the promise, the view is loading before the promise gets returned. ...

Angular’s ng-repeat function is behaving erratically as objects are displayed in the console

Having trouble with my ng-repeat not displaying content. Here is the code for my app.js, client controller, factory, and server controller. Everything else seems to be working fine. I can see all the console logs in Chrome and terminal, but the ng-repeat ...

Use jQuery to switch back and forth between two different sets of classes

I am attempting to switch between two different sets of classes using jQuery. My goal is to change from one custom icon to a font-awesome icon upon clicking an element. While I have been successful in changing a single class, I am facing challenges when tr ...

Implementing Axios interceptor is a common practice in Vue.js applications to central

Hello everyone, I'm facing a problem with the interceptor in VueJS. I can't seem to figure out where the issue lies and it's driving me crazy... I've gone through various tutorials and read numerous posts on stackoverflow, but everythi ...