Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
21
rated 0 times [  28] [ 7]  / answers: 1 / hits: 64719  / 14 Years ago, mon, december 20, 2010, 12:00:00

For instance I have a matrix like this:



|1 2 3|    
|4 5 6|
|7 8 9|


and I need it to convert into a matrix like this:



|1 4 7|    
|2 5 8|
|3 6 9|


What is the best and optimal way to achieve this goal?


More From » matrix

 Answers
29

See article: Transpose An Array In JavaScript and jQuery





function transpose(a) {

// Calculate the width and height of the Array
var w = a.length || 0;
var h = a[0] instanceof Array ? a[0].length : 0;

// In case it is a zero matrix, no transpose routine needed.
if(h === 0 || w === 0) { return []; }

/**
* @var {Number} i Counter
* @var {Number} j Counter
* @var {Array} t Transposed data is stored in this array.
*/
var i, j, t = [];

// Loop through every item in the outer array (height)
for(i=0; i<h; i++) {

// Insert a new row (array)
t[i] = [];

// Loop through every item per item in outer array (width)
for(j=0; j<w; j++) {

// Save transposed data.
t[i][j] = a[j][i];
}
}

return t;
}

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




[#94543] Thursday, December 16, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stacie

Total Points: 476
Total Questions: 92
Total Answers: 102

Location: Bosnia and Herzegovina
Member since Tue, Mar 29, 2022
2 Years ago
stacie questions
Fri, Jun 26, 20, 00:00, 4 Years ago
Thu, Jan 23, 20, 00:00, 4 Years ago
Fri, Aug 30, 19, 00:00, 5 Years ago
Fri, Aug 2, 19, 00:00, 5 Years ago
;