Transpose An Array In JavaScript and jQuery

This JavaScript code adds the functionality to transpose a two-dimensional JavaScript array (array within array). Transposing, in simple terms, is to interchange rows and columns of a matrix (two-dimensional array).

It also extends jQuery to allow transposing of arrays using common jQuery syntax.

The logic behind the code is extremely simple and it is coded keeping performance in mind. The code adds the transpose method to the prototype of the Array object. This allows all arrays to have a transpose() function that can be independently executed.

Installation And Usage of transpose.js

You would require to download the files from this site and include them within the section of your page.

Once you have included the script, you can take any Array object and call the .transpose() method on it. This will return the transposed array.

In the above example, we have transposed a 3 x 2 matrix into a 2 x 3 matrix. If you have FireBug installed, you can see the formatted output by doing console.log() of the transposed variable.

Note: In case you do not have a square matrix, the transposition will still be done on square dimension based on the lengths of first row and first column.

Transpose Array In jQuery

The transpose.js file works seamlessly with jQuery as well. In case jQuery is included in the page (before tranpose.js) it then extends jQuery with the .transpose() method.

The .transpose() method takes in an array object as argument and returns the transposed array.

Download transpose.js JavaScript Prototype and jQuery Plugin

The download package contains transpose.js (minified 322 bytes), transpose.debug.js (full documented version) and some sample HTML files to get you started.

Download [Download not found]

Source Code Snippet

 * Transposes a given array.
 * @id Array.prototype.transpose
 * @author Shamasis Bhattacharya
 * @type Array
 * @return The Transposed Array
 * @compat=ALL
Array.prototype.transpose = function() {

  // Calculate the width and height of the Array
  var a = this,
    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


3 Replies to “Transpose An Array In JavaScript and jQuery”

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.