我有一个数组的数组,就像这样:
[
[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;
}
然而,这看起来很笨重,我觉得应该有更简单的方法来做到这一点。是吗?
ES6 1liner为:
let invert = a => a[0].map((col, c) => a.map((row, r) => a[r][c]))
所以和Óscar的一样,但你更愿意顺时针旋转它:
let rotate = a => a[0].map((col, c) => a.map((row, r) => a[r][c]).reverse())
let a = [
[1,1,1]
, ["_","_","1"]
]
let b = rotate(a);
let c = rotate(b);
let d = rotate(c);
console.log(`a ${a.join("\na ")}`);
console.log(`b ${b.join("\nb ")}`);
console.log(`c ${c.join("\nc ")}`);
console.log(`d ${d.join("\nd ")}`);
收益率
a 1,1,1
a _,_,1
b _,1
b _,1
b 1,1
c 1,_,_
c 1,1,1
d 1,1
d 1,_
d 1,_
这里有很多好答案!我把它们合并成一个答案,并更新了一些代码以获得更现代的语法:
灵感来自Fawad Ghafoor和Óscar Gómez Alcañiz的俏皮话
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]));
}
由Andrew Tatomyr设计的函数方法风格
function transpose(matrix) {
return matrix.reduce((prev, next) => next.map((item, i) =>
(prev[i] || []).concat(next[i])
), []);
}
洛达什/马塞尔的下划线
function tranpose(matrix) {
return _.zip(...matrix);
}
// Without spread operator.
function transpose(matrix) {
return _.zip.apply(_, [[1,2,3], [1,2,3], [1,2,3]])
}
Vigrant的更简单的Lodash/Underscore解决方案
_.unzip(matrix);
香草的方法
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;
}
由伊曼纽尔·萨林根启发的香草ES6方法
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]];
}
}
}