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

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

问题描述

我有一个数组,例如:

<预><代码>[[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[0].map((_, colIndex) => array.map(row => row[colIndex]));

<块引用>

map 为数组中的每个元素依次调用提供的 callback 函数一次,并根据结果构造一个新数组.callback 仅对已赋值的数组索引调用;不会为已删除或从未赋值的索引调用它.

callback 使用三个参数调用:元素的值、元素的索引和被遍历的 Array 对象. [来源]

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((_, 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 中转置二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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