如何从一个二维数组中以数组形式获取所有列,该数组是一个矩形。

huangapple go评论57阅读模式
英文:

How do I get all columns as an array from a 2d array which is a rectangle

问题

A: 我知道map方法返回与主数组相同长度的数组。
我也知道这是一个嵌套循环。

谢谢帮助。

英文:

Q: What do I mean by saying rectangle?
A: [[1,2,3],[1,2,3]] inner arrays have more elements.

Example:

Input: [[1,2,3,4],[1,2,3,4],[1,2,3,4]]
Desired Output: [[1,1,1],[2,2,2],[3,3,3],[4,4,4]]
Output: [[1,1,1],[2,2,2],[3,3,3]]

The reason of the problem: main array has fewer elements, so, when I loop over it, as expected it will return an array with its own length. Shown in the example above.

This is what I tried with an arbitrary example.

const arr = [
      [1, 2, 3],
      [1, 2, 3],
    ];

    const get_column = (arr, i) => arr.map((el) => el[i]);
    const columns = arr.map((_, i, arr) => get_column(arr, i));

    console.log(columns);

I know map method returns an array with the same length as main array.
I also know this is a nested loop.

Thanks for the help.

答案1

得分: 0

假设“rectangle”表示每个子数组的长度相等:

array[0].map((_, i) => {
  return array.map((el, _) => {
    return el[i];
  });
});

或者,更简洁的写法:

array[0].map((_, i) => array.map((el, _) => el[i]));
英文:

Assuming "rectangle" implies each sub-array is of equal length:

array[0].map((_, i) => {
  return array.map((el, _) => {
    return el[i];
  });
});

Or, for short:

array[0].map((_, i) => array.map((el, _) => el[i]));

答案2

得分: 0

const inputArray = [

[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]  

];

const transposeArray = (array) => {

  return array[0].map((_, i) => array.map((el) => el[i]));
};

const outputArray = transposeArray(inputArray);
console.log(outputArray);

转置后的数组存储在 outputArray 变量中。

输出。

[
  [1, 1, 1],
  [2, 2, 2],
  [3, 3, 3],
  [4, 4, 4]
]
英文:
const inputArray = [

[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]  

];

const transposeArray = (array) => {

  return array[0].map((_, i) => array.map((el) => el[i]));
};

const outputArray = transposeArray(inputArray);
console.log(outputArray);

The transposed array is stored in the outputArray variable.

Output.

[
  [1, 1, 1],
  [2, 2, 2],
  [3, 3, 3],
  [4, 4, 4]
]

huangapple
  • 本文由 发表于 2023年8月9日 15:25:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76865486-2.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定