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 transpose.js (version 1.0.0.0, 26.15 kB, 1102 dowloads)

Source Code Snippet