如何从矩形二维数组中提取所有列并转换为数组?
解决矩形数组转置问题
你的核心问题是转置时错误地遍历了原数组的行(主数组元素),导致返回的数组长度等于行数,无法覆盖所有列。要实现正确的转置,需要遍历原数组的列,而非行。
问题分析
原代码中arr.map((_, i) => get_column(arr, i))是遍历原数组的每一行(共N行),所以返回的数组只有N个元素。当原数组的列数M > 行数N时,就会漏掉M-N列的转置结果。
修正方案
因为是矩形数组(所有子数组长度一致),我们可以通过第一个子数组的长度获取列数,然后遍历每个列索引,提取对应列的所有元素:
简洁版代码
const arr = [ [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4] ]; // 遍历原数组的每一列(通过第一个子数组的元素数量确定列数) const transposed = arr[0].map((_, colIndex) => // 对每个列索引,提取所有行的该列元素 arr.map(row => row[colIndex]) ); console.log(transposed); // 输出:[[1,1,1],[2,2,2],[3,3,3],[4,4,4]]
拆分函数版(保留你的getColumn逻辑)
const arr = [ [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4] ]; const get_column = (arr, colIndex) => arr.map(row => row[colIndex]); // 按列数生成转置数组,而非行数 const transposed = Array.from({ length: arr[0].length }, (_, colIndex) => get_column(arr, colIndex) ); console.log(transposed);
验证小例子
对于你提供的2行3列数组:
const arr = [ [1, 2, 3], [1, 2, 3] ]; const transposed = arr[0].map((_, colIndex) => arr.map(row => row[colIndex])); console.log(transposed); // 输出:[[1,1],[2,2],[3,3]],符合预期
内容的提问来源于stack exchange,提问作者mhmtcgrkc
相关产品推荐
相关产品推荐

