首页 > 解决方案 > 如何修改数组数组,具体取决于其中的元素是否与另一个数组数组中的元素匹配?

问题描述

我在 Google 电子表格中有 2 组数组,如下所示:-

var arrayInput = [[ASIAPLY, "9/10/2020"], [PCCS, "9/10/2020"], [SCGM, "9/10/2020"]]

var arrayOuput = [[PCCS, "8/10/2020"]]

如果输出数组中存在第一个索引,我想在 arrayInput 中插入元素/数组的第二个索引。如果不是,我想将整个元素/数组添加到 outputArray 中。我想要的结果是这样的

var arrayOuput = [[PCCS, "9/10/2020", "8/10/2020"], [ASIAPLY, "9/10/2020"], [SCGM, "9/10/2020"]]

我试过这个

function testData() {
  
  // get the range of input data
  var arrayInput = wlSheet.getRange(2, 2, 3, 2).getValues(); 
  
  // get the range of output counter
  var arrayOuput = wlSheet.getRange(2, 7, 1, 2).getValues();
  
  arrayOuput.find((outputRow, i, arr) => {
  
    arrayInput.map((r, index, array) => {
    
    if (r[0] !== outputRow[0]) {
      return wlSheet.getRange(arr.length + 2 + index, 7, 1, 2).setValues([[counter, hyperlinkText]]);
    } else {
      return wlSheet.getRange(i + 2, 8).insertCells(SpreadsheetApp.Dimension.COLUMNS).setValue(hyperlinkText);
    }
    });
  });

}

然而,上面的代码导致了 [[PCCS, "9/10/2020", "8/10/2020"], [PCCS, "9/10/2020"], [ASIAPLY, "9/10/2020" ],[SCGM,“2020 年 9 月 10 日”]];而不是想要的结果。

有没有办法实现我打算在 Google Apps 脚本中做的事情?

提前致谢。

标签: javascriptarraysgoogle-apps-scriptgoogle-sheets

解决方案


如果要插入一个项目,则不能使用Array.prototype.map,因为它将返回一个新数组。

现在我不熟悉谷歌应用程序脚本或与电子表格交互,但基本的 JS 看起来像这样:

您正在尝试的事情可以通过for...of-loop轻松完成

基本步骤是:

  • 我们有两个形状为 a 的数组,key后跟多个值
    • 如果您熟悉 TypeScript 类型:[key: Key, ...values: string[]]
  • 我们想 input output
    • 对于每个元素input
      • 如果输出一个具有相应键的元素:将自己的值附加到它
      • 否则将自我添加到输出
const inArr = [['ASIAPLY', '9/10/2020'], ['PCCS', '9/10/2020'], ['SCGM', '9/10/2020']]
const outArr = [['PCCS', '8/10/2020']]
// iterate over the array elements and use destructuring to
// extract the key form the other values
for (const [key, ...values] of arrayInput) {
  // look for an element in `output` that has that key
  const target = outArr.find(([ky, value]) => ky === key)
  // if we found one, push the values to it
  if (target) target.push(...values)
  // else push your key-values onto the output array
  else outArr.push([key, ...values])
}

使用示例数组的结果是:

[
  [ 'PCCS', '8/10/2020', '9/10/2020' ],
  [ 'ASIAPLY', '9/10/2020' ],
  [ 'SCGM', '9/10/2020' ]
]

由于我们在解构中使用了扩展语法( ...values) ,因此这是一个小迭代器,默认情况下能够处理 0 个或多个值,并且始终会输出适当的结果。

这应该以一种优雅的方式解决这个问题,并且如果需要它很容易修改。


推荐阅读