Home > database >  Deciding on whether to use Bool Check or Try/Catch when checking if String exists in Array
Deciding on whether to use Bool Check or Try/Catch when checking if String exists in Array

Time:12-30

I have no code to share for this particular question as its more of a question of what is a better design choice performance wise.

When checking to see if a string exist in a sheet, would it be best to iterate through a column, get the values. if the value we are searching for is found make a bool true? or would it be best to encapsulate the iteration in a try block and if the string is not found; catch it as a NullReferenceException?

 range = s1.getRange("A2:A").getValues()
 
 for(var i=0;i<range.length;i  ) {
 if(range[i][0] === "searchableString") {
 stringFound = true;

or would it be best to do

 try {
 for(var i=0;i<range.length;i  ) {
 if(range[i][0] === "searchableString") {
 catch(err) {
 err = console.log("string not found, move on");
      }
   }
 }

any advice would be greatly appreciated. Thanks

Using a boolean works but I'm wondering if a try and catch logic block would be beneficial on the offchance the string we are searching for is not found; it can catch the null reference error and move to the next block of code (Whatever that may be)

CodePudding user response:

The best practice is to use enter image description here


Search an Specific Sheet:

function searchSpecificSheet() {
// get the active sheet and creates the finder
  let textFinder = SpreadsheetApp.getActive().getSheetByName("Test 1")
                    .createTextFinder("mobile").findAll();
  // this is just to view the cell where the data is located 
  // this is just for testing and is not necessary
  for (let i = 0; i < textFinder.length; i  ) {
    cell = textFinder[i].getA1Notation()
    console.log("cells: "  cell)
   }
}

Result:

enter image description here


Search under an specific range:

function searchSpecificCell() {
  // get the Range and creates the finder
  let textFinder = SpreadsheetApp.getActive().getSheetByName("Test 1")
  .getRange("B:B").createTextFinder("mobile").findAll();
  
  // this is just to view the cell where the data is located 
  // this is just for testing and is not necessary
  for (let i = 0; i < textFinder.length; i  ) {
    cell = textFinder[i].getA1Notation()
    console.log("cells: "  cell)
   }
}

Result:

enter image description here


You can replace .findAll() with .getCurrentMatch() in any of those samples, and it will return just one cell.

Lastly, if it doesn't find the value, it will return an empty value without errors. Like this:

enter image description here

  • Related