-2
var teams = new Array();
var teamsv2 = new Array();

var num_team = 18;

for (var x = 0; x < num_team; x++) {
  teams[x] = x + 1;
}

for (let tb = 0; tb < teams.length; tb++) {
    teamsv2[[tb][0]] = teams[tb];
}

I created a array called teams2. For example I wanna to add some data this teams2 array.

like this;

teamsv2[[2][0]].push("stackoverflow");
teamsv2[[0][1]],
teamsv2[[1][1]]

I want to fill the second parts of the first index of the array. How can I do that?

TARIK
  • 19
  • 2
  • 1
    You seem to be using an extra pair of braces everywhere. It's generally `obj [x] [y]`. Note that `obj [ [x] [y] ]` is quite different, and probably not what you mean. – Scott Sauyet May 18 '22 at 20:35
  • when I write console.log(teamsv2[1][1]) I want to see like this; 8 – TARIK May 18 '22 at 20:37
  • You haven't made a 2d array so you can't access a nested index. – pilchard May 18 '22 at 20:37
  • @pilchard How can I create 2d array – TARIK May 18 '22 at 20:38
  • last element of teamsv2 array like this = [...,[17][0],[17][1],[17][2],[17][3],[17][4],[17][5] ,[17][6], [17][7]] but I want to add data later in array – TARIK May 18 '22 at 20:47
  • I want to add name in first index of array and other information in other indexes @NinaScholz – TARIK May 18 '22 at 20:48
  • Does this answer your question? [How can I create a two dimensional array in JavaScript?](https://stackoverflow.com/questions/966225/how-can-i-create-a-two-dimensional-array-in-javascript) – Alexei Levenkov May 18 '22 at 20:54

1 Answers1

0

If you want to create a 2-dimensional array, each element of the array should be an array of its own. Right now, you are creating 2 flat arrays.

[[tb][0]] will create a new array of length 1 with the value of tb, access the 0th index, which is just the value of tb. So it's a lot of syntax, but [[tb][0]] is the same as [tb] which is why you are only getting 1-dimensional arrays.

If you "want to fill the second parts of the first index of the array"...

// replace this
teamsv2[[tb][0]] = teams[tb];

// with this
teamsv2[tb] = [ teams[tb] ];

And now you can access the new array like so:

console.log(teamsv2[0][0]); // returns team name

teamsv2[0].push("some info");

console.log(teamsv2[0][1]); // returns "some info"

console.table(teamsv2); // returns something like...
//  (index)   0            1             2
//  0         'Knights'    'some info'
//  1         'Marlins'    'foo'         'example'
//  2         'Volcanoes'  'bar'         'more'
Jacob K
  • 1,096
  • 4
  • 10
  • thank you for the solution! teamsv2[0][2] or teamsv2[0][4] if i want to send data how can i do that – TARIK May 18 '22 at 21:14
  • Could you explain what data you want to send and how it relates to the indices you listed? – Jacob K May 19 '22 at 20:06