Swap rows with columns (transposition) of a matrix in javascript

Bakhtiyor picture Bakhtiyor · Dec 20, 2010 · Viewed 52.1k times · Source

For instance I have a matrix like this:

|1 2 3|    
|4 5 6|
|7 8 9|

and I need it to convert into a matrix like this:

|1 4 7|    
|2 5 8|
|3 6 9|

What is the best and optimal way to achieve this goal?

Answer

hobs picture hobs · Nov 5, 2012

DuckDucking turned up this by Ken. Surprisingly, it's even more concise and complete than Nikita's answer. It retrieves column and row lengths implicitly within the guts of map().

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

console.log(transpose([
    [1,2,3],
    [4,5,6],
    [7,8,9]
]));

[[1,4,5],[2,5,8],[7,8,9]