Search this Blog

Search for:

Subscribe to this Blog

Email Address ...

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.

1

2

3

4

5

6

7

8

9

10

11

12

<html>

<head>

<script type="text/javascript"src="transpose.js"></script>

</head>

<body>

<script type=&quot;text/javascript&quot;>

var matrix = [ [1, 2, 3], [4, 5, 6] ];

var transposed = matrix.transpose();

</script>

</body>

</html>

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.