Google表格:返回多维数组(JavaScript)

问题描述 投票:0回答:2

假设我有四个现有数组:

var one =   ["apple","banana","berry"];
var two =   ["fobar", "barfoo", "farboo"];
var three = [13, 421];
var four =  ["seven", "eight", "eleven"];

如何将它们合并到一个数组中并以最简单的方式返回?我得到的是

var result = [one,two,three,four];

导致

|-----------------------------|
|  apple  |  banana  | berry  |  
|  foobar |  barfoo  | farboo |  
|  13     |  421     |        |
|  seven  |  eight   | eleven |
|-----------------------------|

但是,我真正需要的是:

|------------------------------------|
|  apple  |  foobar  | 13  |  seven  |
|  banana |  barfoo  | 421 |  eight  |
|  berry  |  farboo  |     |  eleven |
|------------------------------------|
javascript arrays multidimensional-array google-apps-script google-sheets
2个回答
1
投票

尝试

var output = one.map(function(e,i){
  return [e].concat([two, three, four].map(function(f){
    return f[i] === undefined ? '': f[i];
  }))
})
console.info(output);

1
投票

JavaScript没有多维数组,它有数组数组。

如果您还没有onetwothreefour数组,您可以使用单个嵌套文字来完成:

var result = [
    ["apple", "fobar", 13, "seven"],
    ["banana", "barfoo", 421, "eight"],
    ["berry", undefined, "eleven"]
];

实例:

var result = [
    ["apple", "fobar", 13, "seven"],
    ["banana", "barfoo", 421, "eight"],
    ["berry", "farboo", undefined, "eleven"]
];
console.log(result);
.as-console-wrapper {
  max-height: 100% !important;
}

如果你已经拥有它们,因为它们是列值的数组,显然你希望子数组是行值,你需要循环:

var result = [];
for (var i = 0; i < 3; ++i) {
    result[i] = [
        one[i], two[i], three[i], four[i]
    ];
}

实例:

var one =   ["apple","banana","berry"];
var two =   ["fobar", "barfoo", "farboo"];
var three = [13, 421];
var four =  ["seven", "eight", "eleven"];
var result = [];
for (var i = 0; i < 3; ++i) {
    result[i] = [
        one[i], two[i], three[i], four[i]
    ];
}
console.log(result);
.as-console-wrapper {
  max-height: 100% !important;
}
© www.soinside.com 2019 - 2024. All rights reserved.