尋找二維陣列的轉置—— JavaScript
我們需要編寫一個 JavaScript 函式,該函式接受一個二維陣列並返回其轉置陣列。
其程式碼如下 −
方法 1:使用 Array.prototype.forEach()
const arr = [
[0, 1],
[2, 3],
[4, 5]
];
const transpose = arr => {
const res = [];
arr.forEach((el, ind) => {
el.forEach((elm, index) => {
res[index] = res[index] || [];
res[index][ind] = elm;
});
});
return res;
};
console.log(transpose(arr));方法 2:使用 Array.prototype.reduce()
const arr = [
[0, 1],
[2, 3],
[4, 5]
];
const transpose = arr => {
let res = [];
res = arr.reduce((acc, val, ind) => {
val.forEach((el, index) => {
acc[index] = acc[index] || [];
acc[index][ind] = el;
});
return acc;
}, [])
return res;
};
console.log(transpose(arr));對於這兩種方法,其在控制檯中的輸出為 −
[ [ 0, 2, 4 ], [ 1, 3, 5 ] ]
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP