Convert a 1D array to 2D array [duplicate]

You can use this code :

const arr = [1,2,3,4,5,6,7,8,9];
    
const newArr = [];
while(arr.length) newArr.push(arr.splice(0,3));
    
console.log(newArr);

http://jsfiddle.net/JbL3p/


Array.prototype.reshape = function(rows, cols) {
  var copy = this.slice(0); // Copy all elements.
  this.length = 0; // Clear out existing array.

  for (var r = 0; r < rows; r++) {
    var row = [];
    for (var c = 0; c < cols; c++) {
      var i = r * cols + c;
      if (i < copy.length) {
        row.push(copy[i]);
      }
    }
    this.push(row);
  }
};

m1 = [1, 2, 3, 4, 5, 6, 7, 8, 9];

m1.reshape(3, 3); // Reshape array in-place.

console.log(m1);
.as-console-wrapper { top:0; max-height:100% !important; }

Output:

[
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]

JSFiddle DEMO