如何从二维数组中提取列?

Raf*_*rmo 3 javascript arrays

设想:

我有一个由值组成的二维数组,例如:

const arr = [ [ 1, 2, 3, 4, 5, 6 ],
              [ 7, 8, 9, 0, 1, 2 ],
              [ 3, 4, 5, 6, 7, 8 ],
              [ 9, 0, 1, 2, 3, 4 ] ];
Run Code Online (Sandbox Code Playgroud)

行数可以变化,但总是会变化是二的倍数。

问题:

如何从该数组中提取列,.map()以便获得每个包含两列的子数组?

例子:

// columns 1 and 2:
ext1 = [ [ 1, 2 ],
         [ 7, 8 ],
         [ 3, 4 ],
         [ 9, 0 ] ];

// columns 3 and 4:
ext2 = [ [ 3, 4 ],
         [ 9, 0 ],
         [ 5, 6 ],
         [ 1, 2 ] ];

// columns 5 and 6:
ext3 = [ [ 5, 6 ],
         [ 1, 2 ],
         [ 7, 8 ],
         [ 3, 4 ] ];
Run Code Online (Sandbox Code Playgroud)

Stu*_*art 7

您可以创建一个这样的函数,根据索引数组选择列:

const getColumns = (arr, indices) => arr.map(row => indices.map(i => row[i]));
getColumns(arr, [0, 1]);    // returns the first two columns
Run Code Online (Sandbox Code Playgroud)

如果最终目标是将数组分成相同大小的块,您可以这样做:

const splitIntoColumnGroups = (arr, width) => 
  [...Array(Math.ceil(arr[0].length/width)).keys()].map(i => 
    arr.map(row => 
      row.slice(i * width, (i + 1) * width)));
Run Code Online (Sandbox Code Playgroud)