我正在尝试创建一个脚本,从超过100.000种产品的列表中筛选出产品。要求是过滤掉不可用的产品,以及我不希望包括的类别中的产品。我有两张表,一张是产品列表,另一张是类别列表,其中包含正确/错误的陈述,当它们应该包括在内时。到目前为止,我的代码如下所示:
function deleteUnavailable() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var rss = ss.getSheetByName("Kategorier");
var rRows = rss.getDataRange();
var rNumRows = rRows.getNumRows();
var rValues = rRows.getValues();
var ass = ss.getSheets()[0];
var aRows = ass.getDataRange();
var aNumRows = aRows.getNumRows();
var aValues = aRows.getValues();
var resultArray = [];
for (var i = 1; i <= aNumRows -1; i++) {
var keep = true;
for (var j = 1; j <= rNumRows -1; j++) {
if (aValues[i][3] == rValues[j][0]) {
if (rValues[j][2] && aValues[i][9] == "JA") {break ;}
else keep = false ; break ;
}
}
if (keep) {
resultArray.push(aValues[i]);
}
}
ass.clear();
ass.getRange(2, 1, resultArray.length, resultArray[0].length).setValues(resultArray);
}正在尝试获取此代码:
for (var i = 1; i <= aNumRows -1; i++) {
var keep = true;
for (var j = 1; j <= rNumRows -1; j++) {
if (aValues[i][3] == rValues[j][0]) {
if (rValues[j][2] && aValues[i][9] == "JA") {break ;}
else keep = false ; break ;
}
}
if (keep) {
resultArray.push(aValues[i]);
}
}要复制产品并发布它们,请执行以下操作:
ass.clear();
ass.getRange(2, 1, resultArray.length, resultArray[0].length).setValues(resultArray);奇怪的是,在我的测试表中使用此代码,但使用不同的位置可以工作,但在这个测试页中不能。谁能告诉我为什么在IF语句中某些产品的条件应该为FALSE时,这段代码却保持不变?
发布于 2020-01-10 17:41:10
所以我的代码运行得很好。只是对它试图处理的信息有一些不一致,这导致代码认为一切都很好。:P
发布于 2020-01-10 21:03:49
如果你想减少索引需求,你可以使用一些Array类方法来让你的逻辑更清晰:
var rValues = rRows.getValues();
var aValues = aRows.getValues();
// Create a pojo hash of information we should keep from rValues
// We care about matching the value in columns A (0) if C (2) is truthy.
const shouldKeep = rValues.slice(1) // skip the header row
.reduce(function (hash, row) {
if (row[2]) {
// Column C is truthy, so store the value from column A
hash[row[0]] = true;
}
return hash;
}, {});
// Inspect all the data rows to see if the compare column D has a
// value in the hash, and if so, that the other column J has the value "JA".
const rowsToKeep = aValues.slice(1)
.filter(function (row) {
return (
// The tenth column must have the value "JA".
row[9] === "JA"
&&
// The fourth column's value must be in our hash
shouldKeep.hasOwnProperty(row[3])
);
});
// Do something with `rowsToKeep`上面的方法还删除了嵌套的for循环,随着rValues和aValues表大小的增长,该循环将显著提高脚本性能,因为只需循环rValues一次即可构建散列。
https://stackoverflow.com/questions/59645730
复制相似问题