![](/img/trans.png)
[英]How to check if one element of an array matches another element in same array?
[英]How to modify an array of array, depending if an element in it matches an element from another array of array?
我在 Google 电子表格中有 2 组数组,如下所示:-
var arrayInput = [[ASIAPLY, "9/10/2020"], [PCCS, "9/10/2020"], [SCGM, "9/10/2020"]]
var arrayOuput = [[PCCS, "8/10/2020"]]
如果第一个索引存在于 outputArray 中,我想在 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, "9/10/2020"]]; 而不是想要的结果。
有没有办法在 Google Apps Script 中实现我打算做的事情?
提前致谢。
如果你想插入一个项目,你不能使用Array.prototype.map
因为它会返回一个新数组。
现在我不熟悉 google 应用程序脚本,也不熟悉与电子表格的交互,但基本的 JS 看起来像这样:
您可以使用for...of-loop轻松完成您正在尝试的操作
基本步骤是:
key
的形状,后面跟着一些值
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 个或多个值,并且将始终输出适当的结果。
这应该以优雅的方式解决这个问题,如果需要,它很容易修改。
/*<ignore>*/console.config({maximize:true,timeStamps:false,autoScroll:false});/*</ignore>*/ const array1 = [ ['ASIAPLY', '9/10/2020'], ['PCCS', '9/10/2020'], ['SCGM', '9/10/2020'], ], array2 = [['PCCS', '8/10/2020']], array2Map = new Map(array2), arrayOutput = array1.map(([k, v]) => [k, v, array2Map.get(k)]); console.log(arrayOutput);
<!-- https://meta.stackoverflow.com/a/375985/ --> <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
要使用setValues
,数组必须具有统一的大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.