Home > Back-end >  Trying to understand Includes Method logic
Trying to understand Includes Method logic

Time:10-22

I have attempted the below script but it is returning the error message "cellRange[i][0].includes is not a function". I am wondering what I am doing wrong here? The idea is to highlight certain rows if the contents of the "cellRange" cells hit a match with the "chars" array.

var chars = ['A', 'B', 'A', 'C', 'B'];
var range = sheet.getRange(2, 2, generatorTab.getLastRow(), 1);
var cellRange = range.getValues();

for(i = 0; i<cellRange.length; i  ){
    if(cellRange[i][0].includes(chars)) {
      sheet.getRange(i, 1, 1, 2).setBackground("#00ffff");
    }
};

CodePudding user response:

From The idea is to highlight certain rows if the contents of the "cellRange" cells hit a match with the "chars" array., in this case, in the case of cellRange[i][0].includes(chars), I thought that it should be chars.includes(cellRange[i][0]). But, in your script, the value of i is different row number from the matched row, because cellRange is retrieved from sheet.getRange(2, 2, generatorTab.getLastRow(), 1). So, it is required to be also modified.

When these points are reflected in your script, how about the following modification?

Modified script:

From:

if(cellRange[i][0].includes(chars)) {
  sheet.getRange(i, 1, 1, 2).setBackground("#00ffff");
}

To:

if (chars.includes(cellRange[i][0])) {
  sheet.getRange(i   2, 1, 1, 2).setBackground("#00ffff");
}

Or, I thought that in your situation, when setBackgrounds is used, the process cost might be reduced a little as follows.

var chars = ['A', 'B', 'A', 'C', 'B'];
var range = sheet.getRange(2, 2, generatorTab.getLastRow(), 1);
var cellRange = range.getValues();
var backgrounds = cellRange.map(([b]) => chars.includes(b) ? Array(2).fill("#00ffff") : Array(2).fill(null));
range.offset(0, -1, backgrounds.length, 2).setBackgrounds(backgrounds);

Note:

  • By the way, about generatorTab.getLastRow(), in this case, it's sheet.getLastRow()?

References:

  • Related