在JavaScript中转置2D数组 [英] Transposing a 2D-array in JavaScript

查看:171
本文介绍了在JavaScript中转置2D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组数组,如:

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?

推荐答案

array[0].map((col, i) => array.map(row => row[i]));




map 按顺序为数组中的每个元素调用一次提供的回调函数,并从结果中构造一个新数组。仅为已分配值的数组的索引调用 callback ;对于已删除或从未分配过值的索引,不会调用它。

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.

回调被调用三个参数:元素的值,元素的索引和遍历的Array对象。 [source]

callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed. [source]

这篇关于在JavaScript中转置2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆