Bakhtiyor Bakhtiyor - 2 months ago 11
Javascript Question

How to convert simple array into two-dimensional array(matrix) in javascript (or jquery)

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

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]]