Convert simple array into two-dimensional array (matrix)

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.


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

You can use the Array.prototype.reduce function to do this in one line.

ECMAScript 6 style:

myArr.reduce((rows, key, index) => (index % 3 == 0 ? rows.push([key]) 
  : rows[rows.length-1].push(key)) && rows, []);

"Normal" JavaScript:

myArr.reduce(function (rows, key, index) { 
  return (index % 3 == 0 ? rows.push([key]) 
    : rows[rows.length-1].push(key)) && rows;
}, []);

You can change the 3 to whatever you want the number of columns to be, or better yet, put it in a reusable function:

ECMAScript 6 style:

const toMatrix = (arr, width) => 
    arr.reduce((rows, key, index) => (index % width == 0 ? rows.push([key]) 
      : rows[rows.length-1].push(key)) && rows, []);

"Normal" JavaScript:

function toMatrix(arr, width) {
  return arr.reduce(function (rows, key, index) { 
    return (index % width == 0 ? rows.push([key]) 
      : rows[rows.length-1].push(key)) && rows;
  }, []);
}