我有n个数组。每行中的行数相同:Array0,Array1,...,Arrayn。
现在我想遍历所有这些人并最终加入他们。将每个数组转置到新创建的ResultArray的列中
for (var ID = 0; ID < n+1; ID++) {
for (var i = 0; i < ("Array" + ID).length; i++) {
ResultArray[i][ID] = ("Array" + ID)[i]
}
}
以下是我想要的示例:
Array0 = [Apple, Banana, Chicken]
Array1 = [5, 7, 8]
Array2 = [High, Low, Low]
ResultArray = [[Apple, 5, High], [Banana, 7, Low], [Chicken, 8, Low]]
答案 0 :(得分:2)
您具有以下数组。
Array0 = ["Apple", "Banana", "Chicken"];
Array1 = [5, 7, 8];
Array2 = ["High", "Low", "Low"];
您要将上面的数组转换为下面的数组。
[["Apple",5,"High"],["Banana",7,"Low"],["Chicken",8,"Low"]]
在您的示例数组中,每个数组的数组长度都是相同的。
如果我的理解是正确的,那么该修改如何?请认为这只是几个答案之一。
var Array0 = ["Apple", "Banana", "Chicken"];
var Array1 = [5, 7, 8];
var Array2 = ["High", "Low", "Low"];
var arrays = [Array0, Array1, Array2]; // Please prepare this.
var res = [];
for (var i = 0; i < arrays[0].length; i++) {
var temp = [];
for (var j = 0; j < arrays.length; j++) {
var ar = arrays[j];
temp.push(ar[i]);
}
res.push(temp);
}
Logger.log(res)
var Array0 = ["Apple", "Banana", "Chicken"];
var Array1 = [5, 7, 8];
var Array2 = ["High", "Low", "Low"];
var numberOfArrays = 3; // Please prepare this. In your case, it's 3.
var res = [];
for (var i = 0; i < Array0.length; i++) {
var temp = [];
for (var j = 0; j < numberOfArrays; j++) {
var ar = eval("Array" + j);
temp.push(ar[i]);
}
res.push(temp);
}
Logger.log(res)
如果我误解了您的问题,而这不是您想要的结果,我深表歉意。
答案 1 :(得分:0)
您还可以使用Array.reduce以更简洁的方式解决此问题:
const arr1 = ["Apple", "Banana", "Chicken"], arr2 = [5, 7, 8], arr3 = ["High", "Low", "Low"],
data = [arr1, arr2, arr3]
let result = data.reduce((acc, c) =>
(c.forEach((x,k) => acc[k].push(x)), acc), Array.from({length: data.length}, () => []))
console.log(result)
或更易读的形式:
const arr1 = ["Apple", "Banana", "Chicken"], arr2 = [5, 7, 8], arr3 = ["High", "Low", "Low"],
data = [arr1, arr2, arr3]
let result = data.reduce((acc, c) => {
c.forEach((x,i) => acc[i].push(x))
return acc
}, Array.from({length: data.length}, () => []))
console.log(result)
想法是merge
这些数组,然后在Array.reduce
已经是accumulator
形式的情况下执行[[],[],[]]
,因此我们只填充每个子数组。
答案 2 :(得分:0)
使用Array.reduce()
查找最长的数组。使用Array.map()
迭代最长的数组,并获取行索引。然后使用第二个Array.map()
从数组中获取行项。
const zip = (...arrs) => arrs
.reduce((r, c) => c.length > r.length ? c : r, []) // get the longest array
.map((_, i) => arrs.map(a => a[i])) // map the longest array to get the current row number, then create the row
const arr1 = ["Apple", "Banana", "Chicken"], arr2 = [5, 7, 8], arr3 = ["High", "Low", "Low"]
const result = zip(arr1, arr2, arr3)
console.log(result)