Transpose in JavaScript

Transpose in JavaScript

Transpose: interchange rows and columns of a matrix (two-dimensional array).

[ 
  [1, 2, 3], 
  [4, 5, 6]
];

↓↓↓

[
  [1, 4],
  [2, 5],
  [3, 6]
]

Long version:

/**
 * http://www.shamasis.net/2010/02/transpose-an-array-in-javascript-and-jquery
 */
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 < 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;
};

Short version:

/**
 * http://www.codesuck.com/2012/02/transpose-javascript-array-in-one-line.html
 */
function transpose(a) {
    return Object.keys(a[0]).map(function (c) {
        return a.map(function (r) {
            return r[c];
        });
    });
}

Yang Zhao

Read more posts by this author.


Comment