So in my javascript I have a huge 1D array and I want to convert it into a 2D array. This is what I have so far, but doesn't seem to work.
var arrLines = strRawContents.split(",");
var array2;
for (int i = 0; i < 98; i++) {
for (int j = 0; j < 5; j++) {
array2[i][j] = arrLines[(j * 98) + i];
}
}
return arrLines
}
This is what I currently have, where I'm trying to make 98 rows and in each row, there is 5 columns. My goal is complicated. If my 1D array were to be [1,2,3,4,5,6,7,8,9,10 and so on], My 2D array at [0][0] should be 1, at [0][1] should be 2 and so on until [0][7] would be 8, then [1][0] would be 9, [1][1] would be 10 and so forth.
1 Answer 1
In every outer loop, create an array. In the inner loop, push contents into it, at the end of the outer loop, push that newly created array into the final 2-d array.
var arrLines = strRawContents.split(",");
var array2 = [];
for (var i = 0; i < 98; i++) {
var arr = [];
for (var j = 0; j < 5; j++) {
arr.push(arrLines[(i * 5) + j]);
}
array2.push(arr);
}
return arr2;
Some mistakes in your original code:
- You need to initialize your
array2to be an empty array. - There's no
intkeyword in JavaScript. Usevarorlet(letis preferred but not all browsers support it yet. - The formula should be
(i * 5) + jnot(j * 98) + i. - The return value should be
array2.
6 Comments
strRawContents and how the final 2-d array should look like. Sorry your comments are not very clear.
var array2 = {};