Skip to content

Instantly share code, notes, and snippets.

@femto113
Last active September 6, 2023 00:28
Show Gist options
  • Save femto113/1784503 to your computer and use it in GitHub Desktop.
Save femto113/1784503 to your computer and use it in GitHub Desktop.
one line transpose for 2-dimensional Javascript arrays
function transpose(a)
{
return a[0].map(function (_, c) { return a.map(function (r) { return r[c]; }); });
// or in more modern dialect
// return a[0].map((_, c) => a.map(r => r[c]));
}
@ibarrajo
Copy link

ibarrajo commented May 4, 2014

Pretty cool, I converted this to coffeescript, It's easier to understand IMHO

transpose = (a) ->
    return a[0].map (_, c) ->
        return a.map (r) ->
            return r[c]

@bsa7
Copy link

bsa7 commented Aug 31, 2014

Nice gist!
Thank you!

@stevetarver
Copy link

Your gist turned up as my first google hit so I thought I would add more coffee: found this on rosetta code (http://rosettacode.org/wiki/Matrix_transposition#CoffeeScript). Note that each map() call costs a function call. Not sure when eliminating a couple of function calls would be significant...

transpose = (matrix) ->
    (t[i] for t in matrix) for i in [0...matrix[0].length]

@lubien
Copy link

lubien commented Feb 18, 2016

ES6 version:

transpose = a => a[0].map((_, c) => a.map(r => r[c]));

(edited, was missing the [0] before the first map)

@qodunpob
Copy link

qodunpob commented Jun 9, 2016

👍

@hongbo-miao
Copy link

hongbo-miao commented Nov 1, 2016

thanks! and ES6 version looks neat!

@tatomyr
Copy link

tatomyr commented Jan 20, 2017

Hmm... a[0].map? What about empty arrays?
lubien's ES6 version works correctly only for square matrix.
The solution I suggest does not rely on any specific part of the matrix (which could crash the code) nor contains itself within (making use of dot notation easier):

transpose = matrix => matrix.reduce(($, row) => row.map((_, i) => [...($[i] || []), row[i]]), [])

transpose([[0, 1], [2, 3], [4, 5]]) // [[0, 2, 4], [1, 3, 5]]

@femto113
Copy link
Author

femto113 commented Jul 31, 2017

@tatomyr empty arrays (or non-2-dimensional arrays) a legit concern for a library method, not sure if it's important for a one liner. Probably best dealt with something like this

function transpose(a)
{
  return a && a.length && a[0].map && a[0].map(function (_, c) { return a.map(function (r) { return r[c]; }); }) || [];
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment