二维数组x,y轴互相转换,二维数组行列互换

// 需求: 根据 [[1,2],[11,22],[111,222]] 得到 [[1,11,111],[2,22,222]]

function getData(list) {
  let result = new Array(list[0].length).fill([])
  list.forEach((item, index) => {
    item.forEach((cItem, cIndex) => {
      result[cIndex] = [...result[cIndex], cItem]
    })
  })
  return result
}

// 原数组:
let list = [
  [1, 2, 3, 4, 5, 6],
  [11, 22, 33, 44, 55, 66],
  [111, 222, 333, 444, 555, 666]
]

getData(list)
// [
//   [1, 11, 111],
//   [2, 22, 222],
//   [3, 33, 333],
//   [4, 44, 444],
//   [5, 55, 555],
//   [6, 66, 666]
// ]

// 同理,转回去也用同样的方法:
const test = getData(list)
getData(test)

// [
//   [1, 2, 3, 4, 5, 6],
//   [11, 22, 33, 44, 55, 66],
//   [111, 222, 333, 444, 555, 666]
// ]

 

posted @ 2022-10-10 16:59  william_new  阅读(162)  评论(0编辑  收藏  举报