An effective method for retrieving elements from a one-dimensional array using nested loops

I have a vector containing data that needs to be stored in the following order:

cAge[0]  = 'Age (1) (1)';
cAge[1]  = 'Age (1) (2)';
cAge[2]  = 'Age (1) (3)';
cAge[3]  = 'Age (2) (1)';
cAge[4]  = 'Age (2) (2)';
cAge[5]  = 'Age (2) (3)';
cAge[6]  = 'Age (3) (1)';
cAge[7]  = 'Age (3) (2)';
cAge[8]  = 'Age (3) (3)';
cAge[9]  = 'Age (4) (1)';
cAge[10] = 'Age (4) (2)';
cAge[11] = 'Age (4) (3)';

This can be achieved with a for loop without any complications:

var cAge = [];

for (var i=1; i<=4; i++) {
  for (var j=1; j<=3; j++) {
    cAge.push('Age (' + i + ')' + ' ' + '(' + j + ')');
  }
}

However, I am facing an issue when trying to display all the elements using a nested loop:

for (var i=1; i<=4; i++) {
  for (var j=1; j<=3; j++) {
    console.log(cAge[j-1]); // <- What should j-1 be?
  }
}

Currently, it outputs:

Age (1) (1)
Age (1) (2)
Age (1) (3)
Age (1) (1)
Age (1) (2)
Age (1) (3)
Age (1) (1)
Age (1) (2)
Age (1) (3)
Age (1) (1)
Age (1) (2)
Age (1) (3)

What should the value of j-1 represent here?

Answer №1

Using nested loops to access elements in a 1-D array:

const cAge = [],
  nrows = 4,
  ncols = 3;

for (var i = 1; i <= nrows; i++) {
  for (var j = 1; j <= ncols; j++) {
    cAge.push("Age (" + i + ")" + " " + "(" + j + ")");
  }
}

for (var i = 0; i < nrows; i++) {
  for (var j = 0; j < ncols; j++) {
    console.log(cAge[i * ncols + j]);
  }
}

Define ncols = 3 in the code.

i value in nested loop j value in nested loop Calculated 1-D index
0 0 0 * 3 + 0 = 0
0 1 0 * 3 + 1 = 1
0 2 0 * 3 + 2 = 2
1 0 1 * 3 + 0 = 3
1 1 1 * 3 + 1 = 4
1 2 1 * 3 + 2 = 5
2 0 2 * 3 + 0 = 6
2 1 2 * 3 + 1 = 7
2 2 2 * 3 + 2 = 8

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

Incorporating a series of image links into a Three.js project with the addition of a

My latest project involves creating a reflection cube with randomly changing images on each side every time the site is reloaded. Here is the code I have written: var imgAr = [ 'sources/instagram2/image1.jpg', 'sources/instagram2/image2.jp ...

Tips on effectively utilizing dynamic data with Google Charts

I am working on creating a dynamic chart using Google Charts with multiple CSV files. I want to display a different chart depending on the selection made by the user. The first file loads successfully and displays a chart, but the $("#selection").change(.. ...

Exploring the interaction between child objects and cube objects in Three.js

I have a main cube object with wireframe: var cubeGeometry = new THREE.CubeGeometry( 50, 50, 50 ); Also, I have some cubes that are not wireframed: var cubeTemp = new THREE.CubeGeometry( 10, 10, 10 ); I want to rotate cubeGeometry and have cubeTemp rot ...

How can I utilize Node JS REST API to serve HTML documents?

After successfully creating a REST API in Node JS, I've encountered an obstacle. app.use('/api', router); This particular code ensures that every URL is prefixed with 'api'. However, what should I do if I want to serve an HTML fi ...

Creating a compact HTTP server in c/c++ and incorporating AJAX capabilities into it

Creating a dynamic webpage that can automatically update information is my goal. I've managed to establish a socket and send HTML and Javascript files from my c/c++ application to the browser. However, now I'm stuck on how to proceed. How do I p ...

Pressing on an HTML element using JavaScript via the Selenium driver does not trigger the action

I'm attempting to use Selenium with Python to click on an element using JavaScript. Here's a snippet of my code: driver.execute_script("els=document.getElementsByClassName('buttons');\ for (var i = 0; i < els.length; i++) { ...

Graph is vanishing while linked

A unique HTML canvas is included in a standalone file called dashboard.html. To display the dashboard on the main homepage (home.html), we utilize ng-view nested within an ng-if directive. Oddly, clicking on the hyperlink "#" from the home page causes th ...

passing an array reference to a C++ function

Here are three methods for passing an array to a function: 1. void updateArray(int array[]) { array[0] = 1111; } void updateArrayByPointer(int * array) { array[0] = 1111; } void updateArrayByReference(int (&array)[]) { array[0] = 1 ...

Styling a <slot> within a child component in Vue.js 3.x: Tips and tricks

I'm currently working on customizing the appearance of a p tag that is placed inside a child component using the slot. Parent Component Code: <template> <BasicButton content="Test 1234" @click="SendMessage('test') ...

What is the best way to loop through a JSON array in JavaScript?

Here is the JSON data I am working with: let jsonData = { "result": [ [ { "PARAM 1": [ { "field": "firstName", "message ...

Utilizing HTML templates efficiently without the need for a view engine

For a new application, we are implementing multiple servers for handling different functions - one server for delivering HTML files, another as a proxy to handle HTTPS requests, and a Java backend with a database. The view server should be simple, with an ...

What is the best way to dismiss the additional modal popup?

Here is an example that I need help with: http://jsfiddle.net/zidski/Mz9QU/1/ When clicking on Link2 followed by Link1, I would like the Link2 box to close automatically. Is there anyone who can assist me with this issue? ...

Redux export does not complete correctly unless brackets are used

I'm trying to understand why the main JS file is having trouble importing todo from './actions' without brackets, while there are no issues with importing todos from './reducers'. Main js-file: import { createStore } from 'r ...

Mongooses do not clutter the array with unnecessary lines

I need help generating a sorted list from the database. Here is my current code: const subs = await Sub.find({}, {userName: 1, score: 1, _id: 0}).sort({ score: 'desc' }); The output I am getting looks like this: { userName: 'test1', ...

I am seeking to consolidate arrays with duplicate tag names into a single grouped array

Here is an example array: Array ( [0] => Array ( [tag_name] => Quant-Arithmetic [student_marks] => 1.05 [total_marks] => 2.00 [student_count] => 1 [level] => Easy ...

When using the e.target.getAttribute() method in React, custom attributes may not be successfully retrieved

I am struggling with handling custom attributes in my changeHandler function. Unfortunately, React does not seem to acknowledge the custom "data-index" attribute. All other standard attributes (such as name, label, etc.) work fine. What could be the issu ...

Exploring the Wonder of MVC with Ajax Calls Handling Multiple Parameters

I've been struggling to send 2 parameters from the View to the controller using an ajax call. Everything was working fine when I had only one parameter, but as soon as I added another, the function stopped working. Below is the Javascript code with a ...

Is there a way to modify the text of image URLs using JavaScript?

My method of replacing a specific word in text works like this: document.body.innerHTML = document.body.innerHTML.replace(/katt/g, "smurf"); However, when I try to replace an image URL in HTML using the same line of code, it doesn't seem to work. H ...

Exploring the Potential of jQuery through iBooks

Would like to know how to fix an issue with an interactive glossary I'm creating for an iBooks eBook. When clicking on a term, the definition should appear at the end of the page. Hiding the definition can be done by clicking on the term again or by c ...

Utilizing JavaScript to create multiple HTML tables from JSON data

Is it necessary to create separate tables in HTML for each set of JSON data when all tables have the same number of columns (2 columns)? I am looking to minimize the JavaScript function that displays the table with the current JSON data. Can I use one tabl ...