Home > Blockchain >  filter google sheet based on cell value using a regex expression that match any numeric values and a
filter google sheet based on cell value using a regex expression that match any numeric values and a

Time:06-10

Below is a code that filters spreadsheet based on specific column values and copy matches to a new spreadsheet

function filterkhaled(){
    var sheet = SpreadsheetApp.getActiveSheet();
    var newSheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet();
    var reg = /^\d $/;
    var data = sheet.getDataRange().getDisplayValues();
    var newData = data.filter(row => ["yes"].includes(row[12]) | row.match(reg));
    newSheet.getRange(1,1,newData.length,newData[0].length).setValues(newData);
  }

I want basically that filter matches the string "yes" or any numeric value, and then copy the corresponding matches into new spreadsheet. The code here row.match(reg)shows the following error TypeError: row.match is not a function is there a way to make the regex filter work?

Here is how the starting table look like source sheet, where green marked rows are to be copied to a new spreadsheet based on the value of column M

The output shall contain all green rows.

CodePudding user response:

Modification points:

  • I thought that the reason for your error of TypeError: row.match is not a function is due to that row is an array.
  • ["yes"].includes(row[12]) is the same with row[12] == "yes".
  • In this case, please use || instead of |.

When these points are reflected in your script, it becomes as follows.

Modified script:

function filterkhaled() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var newSheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet();
  var reg = /^\d $/;
  var data = sheet.getDataRange().getDisplayValues();
  var newData = data.filter(row => row[12] == "yes" || row[12].match(reg));
  if (newData.length == 0) return;
  newSheet.getRange(1, 1, newData.length, newData[0].length).setValues(newData);
}
  • When this script is run, the rows that the value of column "M" is yes or the number are put to the new sheet.

References:

  • Related