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?
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]
]));