MaxxyPoo
MaxxyPoo

Reputation: 27

1D array to 2D array in Javascript

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

Answers (1)

Yangshun Tay
Yangshun Tay

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:

  1. You need to initialize your array2 to be an empty array.
  2. There's no int keyword in JavaScript. Use var or let (let is preferred but not all browsers support it yet.
  3. The formula should be (i * 5) + j not (j * 98) + i.
  4. The return value should be array2.

Upvotes: 1

Related Questions