Search code examples
javascriptgoogle-apps-scriptgoogle-sheets

Google Apps Script: Finding an element in a Column and returning the corresponding row


So i want my program to search for an element in the first column of my google sheets and if the element is found , return the corresponding row .When i test this code, the element even if it is present shows that it isn't.

function doGet(e){
  var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1AssaPoFPcazneN44EjE04fE99MxTaPZg5uMsO1Klh4o/edit#gid=0");
  var sheet = ss.getSheetByName("Sheet1");
  return finds(e,sheet);
}

function doPost(e){
  var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1AssaPoFPcazneN44EjE04fE99MxTaPZg5uMsO1Klh4o/edit#gid=0");
  var sheet = ss.getSheetByName("Sheet1");
  return finds(e,sheet);
  
}

function finds(e,sheet) {
  var records = {};
  var scannedData = e.parameter.sdata;
  var range = sheet.getDataRange().getDisplayValues().map(r => r[0]); // -> get display Data as 1D array - Col A
  var  data = [];
  if(range.includes(scannedData)) { // use includes to see if scannedData is included in the array
       var row_scannedData = range.indexOf(scannedData);
       var result =  sheet.getRange(row_scannedData,1,1,4);  //fetches the entire row belonging to the result
       data.push(result);  //pushes the row in an array
       records.items = data; 
       var finalresult = JSON.stringify(records);
       return ContentService.createTextOutput(result).setMimeType(ContentService.MimeType.JSON);
  }
  return ContentService.createTextOutput("Not Found").setMimeType(ContentService.MimeType.TEXT);
} 

Solution

  • Answer:

    You can do this with a TextFinder.

    Code Sample:

    Assuming that there is only one cell in column A with your serach term:

    function searchColumnA(searchTerm) {
      var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
      var aColumn = sheet.getRange("A1:A" + sheeet.getLastRow());
    
      var tf = aColumn.createTextFinder(searchTerm).findAll(); 
      return tf[0].getRow();
    }
    

    References: