javascriptgoogle-sheetsgoogle-apps-script

Converting index matches Google Sheets formula to Apps script


I need to index matches based on 2 columns and set the Data!I1:I values into the Tab N column.

=arrayformula(iferror( vlookup( G1:G & H1:H,{Data!G1:G&Data!H1:H,Data!I1:I},2,false)))

Worksheet Demo

The formula is working, but I need it to be converted into a Google Apps script.

I have tried, but I am getting an error. searchRow is not a function.

const mainData = ss.getSheetByName("Data");
const tab = ss.getSheetByName("Tab");
const searchValues = mainSS.getRange("G1:H").getValues();
const targetMatch = tab.getRange("G1:H").getValues();                
const matching = searchValues.map(searchRow =>{
const matchRow = targetMatch.find(r => r[0] == searchRow([0]))
return matchRow ? [matchRow([2])] : [null];
})
targetMatch.getRange("N1:N").setValues(matching);

Solution

  • In your situation, how about the following modification?

    Modification points:

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

    Modified script:

    function myFunction() {
      const sheetName1 = "Tab";
      const sheetName2 = "Data";
    
      // Retrieve sheets.
      const ss = SpreadsheetApp.getActiveSpreadsheet();
      const [sheet1, sheet2] = [sheetName1, sheetName2].map(s => ss.getSheetByName(s));
    
      // Retrieve values from both sheets.
      const lastRow1 = sheet1.getLastRow();
      const values1 = sheet1.getRange("G1:H" + lastRow1).getValues();
      const values2 = sheet2.getRange("G1:I" + sheet2.getLastRow()).getValues();
    
      // Create an object for searching.
      const obj2 = new Map(values2.map(([g, h, i]) => [`${g}${h}`, i]));
    
      // Create the result array.
      const res = values1.map(([g, h]) => [obj2.get(`${g}${h}`) || null]);
    
      // Put the result array to column "O" of "Tab" sheet as a sample.
      sheet1.getRange(`O1:O${lastRow1}`).setValues(res);
    }
    

    When this script is run, the result values are put into column "O". Because your Spreadsheet has values in column "N". When you want to put the values to column "N", please modify sheet1.getRange(`O1:O${lastRow1}`).setValues(res); to sheet1.getRange(`N1:N${lastRow1}`).setValues(res);.

    References: