Convert a 1D array to 2D array

I suppose you could do something like this... Just iterate over the array in chunks.

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

// array = input array
// part = size of the chunk
function splitArray(array, part) {
    var tmp = [];
    for(var i = 0; i < array.length; i += part) {
        tmp.push(array.slice(i, i + part));
    }
    return tmp;
}

console.log(splitArray(m1, 3)); // [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]

Obviously there is no error checking, but you can easily add that.

DEMO


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


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/