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?
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?
You can use
Object.keys
andArray.prototype.map
:Just like in any other language:
You just have to construct the 2D array differently in JS. Like this:
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()
.Compact version of Hobs' answer using arrow functions from ES6:
I don't have enough reputation to comment (wtf.), so I need to post Ken's updated version as a separate answer:
See article: Transpose An Array In JavaScript and jQuery