Home > Software engineering >  Google Apps Script search function needs to compare strings containing numbers and letters
Google Apps Script search function needs to compare strings containing numbers and letters

Time:04-14

So I'm building an incredibly simple database (really just a minor in-sheet MVC) to standardize data storage practices in order to automate some things. I'm trying to build a search function so that data entries can be edited, but I'm having trouble getting my search parameters to compare as they come in an "ABC 1234" format. I have a feeling I simply don't know the language well enough yet, but here's my search function;

function search() {

  const searchValue = searchCell.getValue()
  const data = dataWS.getRange("A2:I").getValues()
  data.filter(r => r[8] == searchValue)
  const recordsFound = data.filter(r => r[8] == searchValue)
  if(recordsFound.length == 0) return

  fieldRange.forEach((f,i) => formWS.getRange(f).setValue(recordsFound[0][i 1]))


}

The cell locations and sheet locations and everything are established globally so if there's anything missing here you need, I'll gladly provide it.

Both == and === did not work and I imagine I'm simply missing some knowledge or experience here, but I'm also having trouble tracking down what I'm missing. Tough when you don't know what you don't know. I get the error "TypeError: Cannot read property '1' of undefined" and it points to the if comparison line.

CodePudding user response:

Finding Search Value

function search() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("SheetName");
  const searchValue = sh.getRange("?").getValue();
  const dataWS= ss.getSheetByName("?")
  const data = dataWS.getRange("A2:I"   dataWS.getLastRow()).getValues().filter(r => r[8] == searchValue);//r[8] is column 9
  //I don't know where you're going from here so I'll just logger.log the data
  Logger.log(JSON.stringify(data));
}

Using textfinder is also pretty easy

Using textfinder

function search() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("SheetName");
  const searchValue = sh.getRange("?").getValue();
  const dataWS= ss.getSheetByName("?")
  const data = dataWS.getRange("A2:I"   dataWS.getLastRow()).createTextFinder(searchValue).findAll().map(r => dataWS.getRange(r.getRow(),1,1,dataWS.getLastColumn()).getValues()[0]);
  Logger.log(JSON.stringify(data));
}
  • Related