英文:
How do I get all columns as an array from a 2d array which is a rectangle
问题
问:我说"rectangle"是什么意思?
答:[[1,2,3],[1,2,3]]
内部数组有更多的元素。
示例:
输入:[[1,2,3,4],[1,2,3,4],[1,2,3,4]]
期望输出:[[1,1,1],[2,2,2],[3,3,3],[4,4,4]]
输出:[[1,1,1],[2,2,2],[3,3,3]]
问题的原因是:主数组的元素较少,所以当我循环遍历它时,预期会返回一个与其长度相同的数组。如上面的示例所示。
这是我尝试的一个任意示例。
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);
我知道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]
]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论