列式二维数组解构

时间:2018-10-10 17:51:56

标签: javascript

是否有一种巧妙的方法来解构2D数组以为每个列分配一个变量?

例如:

const matrix = [
  [1,2,3,4,5],
  [1,2,3,4,5],
  [1,2,3,4,5]
]

const [ones, twos, threes, fours, fives] = foo(matrix);

console.log(ones);
// [1, 1, 1]
console.log(twos);
// [2, 2, 2]
etc.

干杯

P

3 个答案:

答案 0 :(得分:0)

hobs answer复制的转置方法

const matrix = [
  [1,2,3,4,5],
  [1,2,3,4,5],
  [1,2,3,4,5]
]
function transpose(a) {
return Object.keys(a[0]).map(function(c) {
    return a.map(function(r) { return r[c]; });
});
}
const [ones, twos, threes, fours, fives] = transpose(matrix);
console.log('ones', ones);

答案 1 :(得分:0)

您需要先转置矩阵。

const
    transpose = array => array.reduce((r, a) => a.map((v, i) => [...(r[i] || []), v]), []),
    matrix = [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]],
    [ones, twos, threes, fours, fives] = transpose(matrix);

console.log(ones);
console.log(twos);
console.log(threes);
console.log(fours);
console.log(fives);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)

const matrix = [
  [1,2,3,4,5],
  [1,2,3,4,5],
  [1,2,3,4,5]
]

function foo(matrix) {
  let columns = []
  for(const i in matrix) {
    for(const j in matrix[i]) {
      columns[j] = columns[j] || []
      columns[j].push(matrix[i][j])
    } 
  }
  return columns
}

const [ones, twos, threes, fours, fives] = foo(matrix);

console.log(ones);
// [1, 1, 1]
console.log(twos);
// [2, 2, 2]