Convert simple array into two-dimensional array (matrix) Convert simple array into two-dimensional array (matrix) javascript javascript

Convert simple array into two-dimensional array (matrix)


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;  }, []);}


This code is generic no need to worry about size and array, works universally

  function TwoDimensional(arr, size)     {      var res = [];       for(var i=0;i < arr.length;i = i+size)      res.push(arr.slice(i,i+size));      return res;    }
  1. Defining empty array.
  2. Iterate according to the size so we will get specified chunk.That's why I am incrementing i with size, because size can be 2,3,4,5,6......
  3. Here, first I am slicing from i to (i+size) and then I am pushing it to empty array res.
  4. Return the two-dimensional array.