Is there a concept in JavaScript that includes a data structure called a "matrix" with elements arranged in a grid-like format accessed by

I'm not familiar with the terminology, but I'd like to simplify it:

var topicList1 =['hello','hallo', ..., 'hej'];
var topicList2 =['a','b',...,'c'];
...
var topicList999 =['x,'y',...,'?'];

So I want to access the data like list[para1][para2], is there an existing data structure for this or do I need to create a complex function with the lists? Keep in mind that sizes of lists vary.

Answer №1

Arrays can be multidimensional, with each row having a different size.

 var matrix = [
   [1, 2, 3],
   [4, 5, 6],
   [7, 8, 9],
   [0]
 ];

The variable "matrix" is an array of length 4. To access a specific value, like the number "5" in the second row, you would use:

 var theFive = matrix[1][1];

You can incrementally build a matrix in JavaScript as well.

 var matrix = [];
 for (var i = 1; i < 10; ++i) {
   var row = ~~((i - 1) / 3);
   if (!matrix[row]) matrix[row] = [];
   matrix[row][(i - 1) % 3] = i;
 }
 matrix.push([0]);

When setting values in an Array, Javascript updates the "length" property accordingly. It doesn't allocate space for null elements, so if you set element number 200 first, the array still only contains one item despite having a length of 201.

Answer №2

Although there isn't a specific data structure designed for this scenario, you can achieve the desired outcome by utilizing arrays in combination.

One way to approach this is by creating a jagged array, which consists of arrays within an array:

var example = [
  ['apple','banana','cherry','date'],
  ['red','blue','green','yellow'],
  ['alpha','beta']
];

It's interesting to note that the inner arrays can have varying lengths, hence the term "jagged."

Answer №3

One of the benefits of ES6 OOP is demonstrated in the following example:

class Matrix extends Array {

   constructor(...rows) {
      if(rows.some( r => !Array.isArray(r)))
       throw new TypeError('Constructor accepts  only rows as array')

      super(...rows)
   }

   push(...rows) {
     if(rows.some( r => !Array.isArray(r)))
       throw new TypeError('Push method accepts array(s)')

     super.push(...rows)

   }

}

Example 1:

https://i.sstatic.net/NLFp4.png

Example 2 :

https://i.sstatic.net/Ho3MP.png

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

Ways to stop users from accidentally changing routes in react router v3

Currently, I am working on creating a custom hook to block users from making unintended route changes like using the back button or refreshing the page. Since I am using react-router v3, the <Prompt /> component in react router v4 is not an option fo ...

Unable to establish a websocket connection with either Amber or NPM, uncertain of the reason

Amber CLI (amberframework.org) - v0.11.3 Crystal 0.27.0 [c9d1eef8f] (2018-11-01) LLVM: 4.0.0 Default target: x86_64-unknown-linux-gnu npm 3.5.2 Attempting to incorporate sockets using Crystal Lang and Amber has hit a snag. Despite following the guidelines ...

The onsubmit function is not functioning correctly in combination with Ajax

My current implementation involves utilizing Ajax and Php for user login validation. Unfortunately, the form onsubmit function is not properly functioning. <form action="loggedin.php" onsubmit="return test()" method="post"> Below is the correspondi ...

Using Promise to manipulate objects and arrays returned from functions

https://i.stack.imgur.com/jvFzC.png router.get('/', function (req, res, next) { var size = req.params.size ? parseInt(req.params.size) : 20; var page = req.params.page ? req.params.page>0 ? (size&(parseInt(req.params.page)-1)) : ...

How to mute a particular warning in development mode with Next.js

Currently in the process of transitioning a CRA app to Next.js in order to enhance SEO. During development, I encountered the following warning: Warning: 'NaN' is an invalid value for the 'left' css style property. I am aware of the s ...

Are there any guidelines or rules outlining what is still considered valid JSONP?

I am looking for information on how to properly parse JSONP messages in .NET and extract the JSON data they contain. Is there a current specification that outlines what constitutes a valid JSONP message? During my research, I came across a blog post from ...

tips for remaining in modal window post form submission

I have a form within a modal window. I am using ajax to load content in the same modal window, but the issue is that it redirects to the main page after submitting the form. How can I ensure that the modal window stays open even after the form submission? ...

The timer is malfunctioning

I am new to JavaScript and looking to create a simple countdown. I came across this script: http://codepen.io/scottobrien/pen/Fvawk However, when I try to customize it with my own settings, nothing seems to happen. Thank you for any assistance! Below is ...

What is the best way to test the output of HTML code in a unit test scenario

I am new to web development and testing, taking it slow. I have a website with a button that reveals information when clicked. How can I create a test case to ensure that the displayed output is correct? I need to verify that the text appears on the scre ...

Dynamically Remove One Form from a Django Formset

I have been using the following code to dynamically add a form to my formset: .html {{ form2.management_form }} <div id="form_set"> {% for form2 in form2.forms %} <table class="table table2" width=100%> ...

Ways to block WebSocket access on a personal computer

Is it possible to protect my server resources from being accessed by other websites, such as example.com, via WebSocket? I want to prevent them from accessing the server using a URL like "ws://47.80.151.189:1234", and utilizing its resources (bandwidth, me ...

Mastering the syntax of Babel in Node.js

Hey there! I've encountered a syntax issue while migrating to babel. The problem lies in importing an unnamed module. In traditional Node.js default import, it's possible to import without specifying the module name and passing in the app. Howeve ...

Exploring the techniques for displaying and concealing div elements with pure JavaScript

Here's an example of code I wrote to show and hide div elements using pure JavaScript. I noticed that it takes three clicks to initially hide the div elements. After that, it works smoothly. I was attempting to figure out how to display the elements ...

Adjust the height of a div using jQuery once the AJAX call retrieves the data

There is a div that always matches the height of the adjacent div, depending on the content loaded in it. This setup was functioning properly until I implemented a search feature using jQuery. Now, when I perform a search, the element used in the jQuery ca ...

Trigger a single occurrence of the function upon element creation and pass it to VueJS methods

Currently, I am working with BootstrapVue and would like to provide a brief overview of my code: I have a v-for loop with inputs that can be dynamically created using a b-button named "addElement". Additionally, I have the option to select an item from a ...

Ways to store information in variables and use it across different blocks in Cypress

Is it feasible to store data in variables and reuse them in other blocks within Cypress.io? For instance, imagine I have a unique name for a device. I aim to retrieve this information and then verify if the title in a new window includes that particular de ...

Navigating Angular.js: finding my way to the endpoint paths

Despite my best efforts and extensive research, I find myself in need of assistance! I have a web application that utilizes node and express on the server side, with Angular on the client side. My issue lies with angular routing. IMPORTANT DETAILS My cur ...

When employing the map function in React, the resulting array is always equal to the last element within

Recently delving into the world of React, I encountered an issue while trying to assign unique ids to an array of objects within a Component's state using the map function. Strangely, despite my efforts, all elements in the resulting array ended up be ...

Process JSON data from an input using Javascript

I am encountering an obstacle at the final step of my data flow process. Currently, I am in the midst of developing an application that retrieves input from an HTML form field and utilizes Ajax to fetch data relevant to the user's input. Allow me to e ...

What is the best way to set up an external site iframe that utilizes PHP as a proxy on my web server without encountering CORS issues?

I came across a tutorial on using curl in php, and here is what I have implemented so far: index.html: <!DOCTYPE html> <html> <head> </head> <body> <iframe src="fetch.php" width="800" height="500"></iframe> </ ...