How To Write Code
That Doesn't Suck

wry observations from the deep end of the software cesspool


transpose 2-dimensional Javascript array in one line

There are quite a few libraries that implement a transpose function for arrays, but sometimes you don't want the hassle of installing them or the added dependencies. I'm sure I'm not the first to use this approach but most snippets found by a quick search are too verbose to comfortably drop in for a single use.
Update April 2014: It occurred to me the other day that the magic mentioned below is unneeded, as map already provides the column indexes as the second argument. I've updated the gist so the following remark is no longer relevant. The most magical bit here is to use Object.keys() on the first row of the array which yields an array of column indexes, which we can then use map() on to extract each column in turn. Love to see a terser implementation if you've found one.


Joris Kroos said...

awesome :)

divyanshu said...

Godlike man...!!!

Nicholas Grealy said...

Very nice!

Balázs Orbán said...

hei, i am a beginner, and i would like to know how it works? where should write in the array name?

anon said...

Very nice function. Here's a terser version if you support ES6

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

Scott Sauyet said...

@anon: If you're going to ES6, you might as well go all the way:

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

yogesh kumar said...

This is an awesome post. Really very informative and creative contents. This concept is a good way to enhance knowledge. I like it and help me to development very well. Thank you for this brief explanation and very nice information. Well, got good knowledge.
WordPress development company in Chennai

Post a Comment