Organizational Research By

Surprising Reserch Topic

to swap rows with columns of matrix in javascript or jquery


to swap rows with columns of matrix in javascript or jquery  using -'javascript,jquery,matrix,multidimensional-array,swap'

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?
    

asked Sep 9, 2015 by AnitaTrudel
0 votes
52 views



Related Hot Questions

5 Answers

0 votes

see http://www.shamasis.net/2010/02/transpose-an-array-in-javascript-and-jquery

transpose = function(a) {

  // Calculate the width and height of the Array
  var w = a.length ? a.length : 0,
    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

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

answered Sep 9, 2015 by OnaMajor
0 votes

Googling turned up this. Surprisingly, it's even more concise and complete than Nikita's answer. It retrieves column and row lengths implicitly within the guts of map().

function transpose(a) {
    return Object.keys(a[0]).map(
        function (c) { return a.map(function (r) { return r[c]; }); }
        );
    }

It worked on all my 2-D arrays (but they did all have consistent array lengths).

answered Sep 9, 2015 by ReyHutto
0 votes

Just like in any other language

int[][] copy = new int[columns][rows];
for (int i = 0; i < rows; ++i) {
    for (int j = 0; j < columns; ++j) {
        copy[j][i] = original[i][j];
    }
}

You just have to use array-access methods specific for your language.

answered Sep 9, 2015 by SteDelossan
0 votes

Create this function:

   function transpose(arr) {
        return Object.keys(arr[0]).map(function (c) {
            return arr.map(function (r) {
                return r[c];
            });
        });
    }

and then:

var transposedArray = transpose(originalArray);

answered Sep 9, 2015 by EricaBrockma
0 votes

I don't have enough reputation to comment (wtf.), so I need to post Ken's updated version as a separate answer:

function transpose(a) {
    return a[0].map(function (_, c) { return a.map(function (r) { return r[c]; }); });
}
answered Sep 9, 2015 by Veronique69A

...