# 用JavaScript转置2D数组

2020/10/29 14:22 · javascript ·  · 0评论

``````[
[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;
}
``````

``````array[0].map((_, colIndex) => array.map(row => row[colIndex]));
``````

`map``callback`依次为数组中的每个元素调用提供的函数，然后从结果中构造一个新的数组。`callback`仅对已分配值的数组索引调用；对于已删除或从未分配值的索引，不会调用它。

`callback`使用三个参数调用：元素的值，元素的索引和要遍历的Array对象。[资源]

``````transpose = m => m[0].map((x,i) => m.map(x => x[i]))
``````

``````_.zip.apply(_, [[1,2,3], [1,2,3], [1,2,3]])
``````

`lodash`/`underscore`和的最短方法`es6`

``````_.zip(...matrix)
``````

`matrix`可能在哪里

``````const matrix = [[1,2,3], [1,2,3], [1,2,3]];
``````

``````function transpose(matrix) {
return matrix[0].map((col, i) => matrix.map(row => row[i]));
}

function transpose(matrix) {
return matrix[0].map((col, c) => matrix.map((row, r) => matrix[r][c]));
}
``````

``````function transpose(matrix) {
return matrix.reduce((prev, next) => next.map((item, i) =>
(prev[i] || []).concat(next[i])
), []);
}
``````

Lodash / Undercore由marcel

``````function tranpose(matrix) {
return _.zip(...matrix);
}

// Without spread operator.
function transpose(matrix) {
return _.zip.apply(_, [[1,2,3], [1,2,3], [1,2,3]])
}
``````

``````function transpose(matrix) {
const rows = matrix.length, cols = matrix[0].length;
const grid = [];
for (let j = 0; j < cols; j++) {
grid[j] = Array(rows);
}
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
grid[j][i] = matrix[i][j];
}
}
return grid;
}
``````

``````function transpose(matrix) {
for (var i = 0; i < matrix.length; i++) {
for (var j = 0; j < i; j++) {
const temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
}

// Using destructing
function transpose(matrix) {
for (var i = 0; i < matrix.length; i++) {
for (var j = 0; j < i; j++) {
[matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
}
}
}
``````

``````[[0, 1], [2, 3], [4, 5]].reduce((prev, next) => next.map((item, i) =>
(prev[i] || []).concat(next[i])
), []); // [[0, 2, 4], [1, 3, 5]]
``````

``````function transpose(array) {
return array.reduce((prev, next) => next.map((item, i) =>
(prev[i] || []).concat(next[i])
), []);
}

console.log(transpose([[0, 1], [2, 3], [4, 5]]));
``````

``````const transpose = matrix => matrix.reduce(
(\$, row) => row.map((_, i) => [...(\$[i] || []), row[i]]),
[]
)
``````

``````function transpose(arr,arrLen) {
for (var i = 0; i < arrLen; i++) {
for (var j = 0; j <i; j++) {
//swap element[i,j] and element[j,i]
var temp = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = temp;
}
}
}
``````

``````// Get just the first row to iterate columns first
var t = matrix[0].map(function (col, c) {
// For each column, iterate all rows
return matrix.map(function (row, r) {
return matrix[r][c];
});
});
``````

``````const
transpose = array => array.reduce((r, a) => a.map((v, i) => [...(r[i] || []), v]), []),
matrix = [[1, 2, 3], [1, 2, 3], [1, 2, 3]];

console.log(transpose(matrix));``````

``````const transpose = a => R.map(c => R.map(r => r[c], a), R.keys(a[0]));

console.log(transpose([
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
])); // =>  [[1,5,9],[2,6,10],[3,7,11],[4,8,12]]``````
``<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.22.1/ramda.min.js"></script>``

``````function transpose(matrix) {
return zeroFill(getMatrixWidth(matrix)).map(function(r, i) {
return zeroFill(matrix.length).map(function(c, j) {
return matrix[j][i];
});
});
}

function getMatrixWidth(matrix) {
return matrix.reduce(function (result, row) {
return Math.max(result, row.length);
}, 0);
}

function zeroFill(n) {
return new Array(n+1).join('0').split('').map(Number);
}
``````

``````function transpose(m){return zeroFill(m.reduce(function(m,r){return Math.max(m,r.length)},0)).map(function(r,i){return zeroFill(m.length).map(function(c,j){return m[j][i]})})}function zeroFill(n){return new Array(n+1).join("0").split("").map(Number)}
``````

``````// Create a 5 row, by 9 column matrix.
var m = CoordinateMatrix(5, 9);

// Make the matrix an irregular shape.
m[2] = m[2].slice(0, 5);
m[4].pop();

// Transpose and print the matrix.
println(formatMatrix(transpose(m)));

function Matrix(rows, cols, defaultVal) {
return AbstractMatrix(rows, cols, function(r, i) {
return arrayFill(cols, defaultVal);
});
}
function ZeroMatrix(rows, cols) {
return AbstractMatrix(rows, cols, function(r, i) {
return zeroFill(cols);
});
}
function CoordinateMatrix(rows, cols) {
return AbstractMatrix(rows, cols, function(r, i) {
return zeroFill(cols).map(function(c, j) {
return [i, j];
});
});
}
function AbstractMatrix(rows, cols, rowFn) {
return zeroFill(rows).map(function(r, i) {
return rowFn(r, i);
});
}
/** Matrix functions. */
function formatMatrix(matrix) {
return matrix.reduce(function (result, row) {
return result + row.join('\t') + '\n';
}, '');
}
function copy(matrix) {
return zeroFill(matrix.length).map(function(r, i) {
return zeroFill(getMatrixWidth(matrix)).map(function(c, j) {
return matrix[i][j];
});
});
}
function transpose(matrix) {
return zeroFill(getMatrixWidth(matrix)).map(function(r, i) {
return zeroFill(matrix.length).map(function(c, j) {
return matrix[j][i];
});
});
}
function getMatrixWidth(matrix) {
return matrix.reduce(function (result, row) {
return Math.max(result, row.length);
}, 0);
}
/** Array fill functions. */
function zeroFill(n) {
return new Array(n+1).join('0').split('').map(Number);
}
function arrayFill(n, defaultValue) {
return zeroFill(n).map(function(value) {
return defaultValue || value;
});
}
/** Print functions. */
function print(str) {
str = Array.isArray(str) ? str.join(' ') : str;
return document.getElementById('out').innerHTML += str || '';
}
function println(str) {
print.call(null, [].slice.call(arguments, 0).concat(['<br />']));
}``````
``````#out {
white-space: pre;
}``````
``<div id="out"></div>``

ES6 1liners为：

``````let invert = a => a[0].map((col, c) => a.map((row, r) => a[r][c]))
``````

``````let rotate = a => a[0].map((col, c) => a.map((row, r) => a[r][c]).reverse())
``````

``````    function rotateCounterClockwise(a){
var n=a.length;
for (var i=0; i<n/2; i++) {
for (var j=i; j<n-i-1; j++) {
var tmp=a[i][j];
a[i][j]=a[j][n-i-1];
a[j][n-i-1]=a[n-i-1][n-j-1];
a[n-i-1][n-j-1]=a[n-j-1][i];
a[n-j-1][i]=tmp;
}
}
return a;
}

function rotateClockwise(a) {
var n=a.length;
for (var i=0; i<n/2; i++) {
for (var j=i; j<n-i-1; j++) {
var tmp=a[i][j];
a[i][j]=a[n-j-1][i];
a[n-j-1][i]=a[n-i-1][n-j-1];
a[n-i-1][n-j-1]=a[j][n-i-1];
a[j][n-i-1]=tmp;
}
}
return a;
}
``````

``````function transpose(matrix) {
const rows = matrix.length
const cols = matrix[0].length

let grid = []
for (let col = 0; col < cols; col++) {
grid[col] = []
}
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
grid[col][row] = matrix[row][col]
}
}
return grid
}
``````

``````var arr = [
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]
];

/*
* arr[0].length = 4 = number of result rows
* arr.length = 3 = number of result cols
*/

var result = Array.from({ length: arr[0].length }, function(x, row) {
return Array.from({ length: arr.length }, function(x, col) {
return arr[col][row];
});
});

console.log(result);``````

``````var arr = [
[1, 2],
[1, 2, 3],
[1, 2, 3, 4]
];

/*
* arr[0].length = 4 = number of result rows
* arr.length = 3 = number of result cols
*/

var result = Array.from({ length: arr.reduce(function(max, item) { return item.length > max ? item.length : max; }, 0) }, function(x, row) {
return Array.from({ length: arr.length }, function(x, col) {
return arr[col][row];
});
});

console.log(result);``````
``````const transpose = array => array[0].map((r, i) => array.map(c => c[i]));
console.log(transpose([[2, 3, 4], [5, 6, 7]]));``````

``````var transpose = as => as.length ? as[0].length ? [ as.reduce( (rs,a) => a.length ? ( rs.push(a[0])
, rs
)
: rs
, []
)
, ...transpose(as.map(a => a.slice(1)))
]
: transpose(as.slice(1))
: [],
mtx       = [[1], [1, 2], [1, 2, 3]];

console.log(transpose(mtx))``````
``````.as-console-wrapper {
max-height: 100% !important
}``````
``````function invertArray(array,arrayWidth,arrayHeight) {
var newArray = [];
for (x=0;x<arrayWidth;x++) {
newArray[x] = [];
for (y=0;y<arrayHeight;y++) {
newArray[x][y] = array[y][x];
}
}
return newArray;
}
``````

``````a[0].map((col, i) => a.map(([...row]) => row[i]))
``````
``````reverseValues(values) {
let maxLength = values.reduce((acc, val) => Math.max(val.length, acc), 0);
return [...Array(maxLength)].map((val, index) => values.map((v) => v[index]));
}
``````

``````    transposeArray: function (mat) {
let newMat = [];
for (let j = 0; j < mat[0].length; j++) {  // j are columns
let temp = [];
for (let i = 0; i < mat.length; i++) {  // i are rows
temp.push(mat[i][j]);  // so temp will be the j(th) column in mat
}
newMat.push(temp);  // then just push every column in newMat
}
return newMat;
}
``````

TypeScript中的一种无库实现，适用于不会截断数组的任何矩阵形状：

``````const rotate2dArray = <T>(array2d: T[][]) => {
const rotated2d: T[][] = []

return array2d.reduce((acc, array1d, index2d) => {
array1d.forEach((value, index1d) => {
if (!acc[index1d]) acc[index1d] = []

acc[index1d][index2d] = value
})

return acc
}, rotated2d)
}
``````