javascript - 在 JavaScript 中转置二维数组

标签 javascript arrays matrix transpose

我有一个数组数组,类似于:

[
    [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 provided callback 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/

相关文章:

javascript - 我的代码中出现循环复杂度错误

javascript - RoR GMaps 应用程序中的无效值错误 - 无需更改代码

c - 如何找到数组的大小(从指向数组第一个元素的指针)?

javascript - 放入时 undefined object throw new Error(error.response);

javascript - 使用 jquery 多次对同一个 id 执行点击功能

javascript - 将数组从一种格式转换为另一种格式时出现问题

php - 转义 DB 整个数组

r - 如何在 R 中找到矩阵的所有可能排列?

matlab - 我如何在 Matlab 中标记两个向量?

c++ - 转置 4x4 字节矩阵的最快方法