[英]Google Script/sheets - How to make a script run faster during a loop using …new Set()
Based on the great support by @ziganotschka on this question , we have the following code.基于@ziganotschka对此问题的大力支持,我们有以下代码。 For each of reference, here's a link to the demo sheet posted on the original question.
对于每个参考,这里是原始问题上发布的演示表的链接。
function change_row_color() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
var range = spreadsheet.getDataRange();
var rangeData = range.getValues();
var lastRow = spreadsheet.getLastRow();
var previousclient = rangeData[0][4];
console.log(previousclient);
var colors = [[0,0,0,0,0]];
for ( j = 1 ; j < lastRow; j++){
var currentclient = rangeData[j][4];
console.log(previousclient," ",currentclient);
if (previousclient != currentclient) {
colors.push(["#cc4125","#cc4125","#cc4125","#cc4125","#cc4125"]);
previousclient = currentclient;
} else{
colors.push([0,0,0,0,0]);
}
}
range.setBackgrounds(colors);
}
The script is running great, but it's running rather slow.该脚本运行良好,但运行速度相当慢。 My test array has 350 rows and it takes about 20s to run.
我的测试数组有 350 行,运行大约需要 20 秒。 My actual array has 10K+ rows, and growing.
我的实际数组有 10K+ 行,并且还在增长。 Once I run this code on the real array, I'd like to drop it to below 5s.
在真实数组上运行此代码后,我想将其降至 5 秒以下。 ziganotschka suggested to use...new Set().
ziganotschka 建议使用...new Set()。 I'd love you input on this.
我希望你能对此提出意见。
To apply a given style for all the row where the value in the E column is the same as the previous row.为 E 列中的值与前一行相同的所有行应用给定样式。
In your sheet:在您的工作表中:
A2:Z
A2:Z
Custom formula is
Custom formula is
=$E2=$E1
// change the value of E is you need to make the test on an other row.=$E2=$E1
// 改变 E 的值是你需要在另一行上进行测试。 Choose your wanted formatting style.选择您想要的格式样式。
May not be any faster but you can give it a try.可能不会更快,但您可以尝试一下。
function change_row_color() {
var ss=SpreadsheetApp.getActive()
var sh=ss.getSheetByName('Sheet1');
var rg=sh.getDataRange();
var vs=rg.getValues();
var colors=rg.getBackgrounds();
colors.map(function(r){return r.fill('#000000')});//this is not necessary if the backgrounds always start as black.
var pc=vs[0][4];
vs.forEach(function(r,i){
if(i>0 && r[4]!=pc) {
colors[i].fill("#cc4125");
pc=r[4];
}
});
rg.setBackgrounds(colors);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.