Reputation: 27
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.
Upvotes: 1
Views: 1723
Reputation: 53169
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:
array2
to be an empty array.int
keyword in JavaScript. Use var
or let
(let
is preferred but not all browsers support it yet.(i * 5) + j
not (j * 98) + i
.array2
.Upvotes: 1