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]]
This package consists of a function called numpy. reshape which is used to convert a 1-D array into a 2-D array of required dimensions (n x m). This function gives a new required shape without changing the data of the 1-D array.
Create a 2d array of appropriate size. Use a for loop to loop over your 1d array. Inside that for loop, you'll need to figure out where each value in the 1d array should go in the 2d array. Try using the mod function against your counter variable to "wrap around" the indices of the 2d array.
int rows = 4; int cols = 6; int array1D[rows*cols] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24} int array2D[rows][cols]; int offset = 2; //Offset is always going to be 2 for(int i = 0; i < cols; i++) for(int j = 0; j < rows; i++) array2D[j][i] = array1D[i + j*offset];
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With