I've got an array of arrays, something like:
[
[1,2,3],
[1,2,3],
[1,2,3],
]
I would like to transpose it to get the following array:
[
[1,1,1],
[2,2,2],
[3,3,3],
]
It's not difficult to programmatically do so using loops:
function transposeArray(array, arrayLength){
var newArray = [];
for(var i = 0; i < array.length; i++){
newArray.push([]);
};
for(var i = 0; i < array.length; i++){
for(var j = 0; j < arrayLength; j++){
newArray[j].push(array[i][j]);
};
};
return newArray;
}
This, however, seems bulky, and I feel like there should be an easier way to do it. Is there?
Neat and pure:
Previous solutions may lead to failure in case an empty array is provided.
Here it is as a function:
Update. It can be written even better with spread operator:
If you have an option of using Ramda JS and ES6 syntax, then here's another way to do it:
You can achieve this without loops by using the following.
Array
Array.prototype.map
Array.prototype.reduce
Array.prototype.join
String.prototype.split
It looks very elegant and it does not require any dependencies such as jQuery of Underscore.js.
Minified
Here is a demo I threw together. Notice the lack of loops :-)
If using RamdaJS is an option, this can be achieved in one line:
R.transpose(myArray)
I think this is slightly more readable. It uses
Array.from
and logic is identical to using nested loops:If you are dealing with arrays of unequal length you need to replace
arr[0].length
with something else: