38

I am working on a program where I have to read the values from a textfile into an 1D array.I have been succesfull in getting the numbers in that 1D array.

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

but I want the array to be

m1=[[1,2,3],[4,5,6],[7,8,9]]
j08691
  • 204,283
  • 31
  • 260
  • 272
Shweta Gupta
  • 726
  • 2
  • 6
  • 12

4 Answers4

91

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/

René K
  • 337
  • 5
  • 14
Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75
7

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

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • How to generalize this kind of "reshape" function so that it can reshape a one dimentional array to more than two dimensional array? I.e. an (1x24) array can be reshaped to (2x12), or (2x3x4), or (2x2x2x3), etc. – oat Oct 05 '21 at 16:25
3

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

brbcoding
  • 13,378
  • 2
  • 37
  • 51
1

There are so many ways to do the same thing:

var m = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var n = [];
var i = 0;
for (l = m.length + 1; (i + 3) < l; i += 3) {
    n.push(m.slice(i, i + 3));
}
// n will be the new array with the subarrays

The above is just one.

Whymarrh
  • 13,139
  • 14
  • 57
  • 108