我有一个数组数组,类似于:
[
[1,2,3],
[1,2,3],
[1,2,3],
]
我想转置它以获得以下数组:
[
[1,1,1],
[2,2,2],
[3,3,3],
]
使用循环以编程方式执行此操作并不困难:
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;
}
然而,这看起来很笨重,我觉得应该有一种更简单的方法来做到这一点。有吗?
最佳答案
output = array[0].map((_, colIndex) => array.map(row => row[colIndex]));
map
calls a providedcallback
function once for each element in an array, in order, and constructs a new array from the results.callback
is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.
callback
is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed. [source]
关于javascript - 在 JavaScript 中转置二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17428587/