A Place For Answers

Posts tagged “Internet Explorer 9

JavaScript Matrix Transposition

Lately I found myself using a small piece of code multiple times for multiple projects so I thought I’d share it with you. I wrote this because, although there are code snippets that does this, I needed a version that would support Internet Explorer 7.

The code swaps the rows with the columns and vice versa of a two dimensional array in JavaScript, of course the algorithm can be mimicked in other languages

function transpose(origin) {
    var result = [];
    for (var i = 0; i < origin[0].length; i++) {
        var temp = [];
        for (var j = 0; j < origin.length; j++) {
            temp.push(origin[j][i]);
        };
        result.push(temp);
    };
    return result;
}

If you don’t need support for older browsers though i highly suggest you use this snippet by Shamasis Bhattacharya from his blog:

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

Remember to stay tuned.

Advertisements