Bakhtiyor - 10 months ago 46

Javascript Question

Imagine I have an array

`A = Array(1, 2, 3, 4, 5, 6, 7, 8, 9)`

And I want it to convert into 2-dimensional array (matrix of N x M), for instance like this:

`A = Array(Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9))`

Note, that rows and columns of the matrix is changeable.

Answer Source

Something like this?

```
function listToMatrix(list, elementsPerSubArray) {
var matrix = [], i, k;
for (i = 0, k = -1; i < list.length; i++) {
if (i % elementsPerSubArray === 0) {
k++;
matrix[k] = [];
}
matrix[k].push(list[i]);
}
return matrix;
}
```

Usage:

```
var matrix = listToMatrix([1, 2, 3, 4, 4, 5, 6, 7, 8, 9], 3);
// result: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
```