0

I need to store the following data in a vector (in this 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)';

I can do it with a for loop without problems:

var cAge = [];

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

However I am not able to show all of them using the following 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?
  }
}

It produces:

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 j-1 be?

1
  • You are pushing data in the 1-d array. So just use forEach or for-loop Commented Apr 15, 2021 at 4:49

1 Answer 1

2

Accessing elements from a 1-D array using nested loops:

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]);
  }
}

Here, ncols = 3

i in nested loop j in nested loop 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
Sign up to request clarification or add additional context in comments.

1 Comment

@manooooh Please check if this solves your problem, let me know if you have any issues.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.