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

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]

Leave a Comment