转置矩阵
需求
解题
const arr1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
const arr2 = [[1, 2, 3], [4, 5, 6]]
function fn(arr) {
return arr[0].map((item, i) => arr.map(jtem => jtem[i]))
}
const res1 = fn(arr1)
const res2 = fn(arr2)
console.log(res1, res2)
结果预览:
思路
- 原始方法
function fn(arr) {
const res = []
for (let i = 0; i < arr[0].length; i++) {
const arrItem = []
arr.forEach(item => {
arrItem.push(item[i])
})
res.push(arrItem)
}
return res
}
- 简化一下,用map替换for循环
function fn(arr) {
return arr[0].map((item, i) => {
const arrItem = []
arr.forEach(jtem => {
arrItem.push(jtem[i])
})
return arrItem
})
}
- map彻底一点
function fn(arr) {
return arr[0].map((item, i) => {
return arr.map(jtem => jtem[i])
})
}
- 最终结果
function fn(arr) {
return arr[0].map((item, i) => arr.map(jtem => jtem[i]))
}