I'm looking for some help on trying to combine a formula in excel to apps script function.
Below image shows what result is expected and how I have incorporated that result using excel formula combining COUNTIF and VLOOKUP. It will be really helpful if someone can suggest me how I can incorporate it using apps script in Google sheets without using this formula.
Image for the expected result using 2 tables and the formula used to get that output
I'm not 100% certain on what you're looking for, but I have come up with a script that completes what I believe you're asking.
/** @OnlyCurrentDoc */
function getMetric2() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Sheet1') //change to the name of your sheet
var uniqueRange = sheet.getRange('A13:A19');
var uniqueIds = sheet.getRange('A13:A19').getValues(); //change range to the keys in the final output table
var findKey = sheet.getRange('A3:A5').getValues(); //change range to table 1 unique keys
var lastKey;
for(var i = 0; i < uniqueIds.length; i++) {
//i = row
for(var j = 0; j < uniqueIds[i].length; j++) {
if(lastKey == uniqueIds[i][j]) break;
//j = column
var trueRow = 13+i; //change constant to the row number that var uniqueIds starts at
var row = findKey.findIndex(row => row.includes(uniqueIds[i][j]));
var col = findKey[row].indexOf(uniqueIds[i][j]);
var foundRow = row+3; //change constant to the row number that var findKey starts at
let metric2 = sheet.getRange('C'+foundRow).getValue();
sheet.getRange('C'+trueRow).setValue(metric2);
lastKey = uniqueIds[i][j];
}
}
};
This formula iterates through the IDs from the Final Output table, finds them in Table 1, and returns the corresponding Metric2 value for each.
Linked below is the sheet I used to create and test this. Edit permissions are on, and you should be able to click the button to see the script run.
https://docs.google.com/spreadsheets/d/1eJFm5YpL18X5hqZ5tKnHgT5T60dKMSq18bWqibriRqk/edit?usp=sharing
Please let me know if you have any issues with this, or if it wasn't what you were looking for.