Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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]] 
like image 595
Shweta Gupta Avatar asked Mar 17 '14 20:03

Shweta Gupta


People also ask

How do you convert 1D data into 2D data?

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.

How do you make a 1D array into a 2D array in Java?

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.

How do you convert a 1D array to a 2D array in CPP?

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];


2 Answers

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/

like image 186
Karl-André Gagnon Avatar answered Sep 28 '22 00:09

Karl-André Gagnon


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

like image 25
Mr. Polywhirl Avatar answered Sep 28 '22 02:09

Mr. Polywhirl