Skip to content

Instantly share code, notes, and snippets.

@deepakness
Last active June 29, 2023 05:32
Show Gist options
  • Save deepakness/0e437ff56f703121b0c636c3ee1580d9 to your computer and use it in GitHub Desktop.
Save deepakness/0e437ff56f703121b0c636c3ee1580d9 to your computer and use it in GitHub Desktop.
Create comparisons of "Product 1" vs "Product 2" right inside Google Sheets.
// Add the function to main menu
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('🎉')
.addItem("Create Comparisons", "productComparison")
.addToUi();
}
// Function to create comparisons
function productComparison() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var data = sheet.getDataRange().getValues();
var comparisonData = [];
// Creating sheet "Comparison" and setting the headers dynamically
var comparisonSheet = ss.insertSheet("Comparison");
var headers = [];
data[0].forEach(function(e) {
headers.push(e + ' 1');
headers.push(e + ' 2');
});
comparisonSheet.appendRow(headers);
// Creating comparison data
for (var i = 1; i < data.length; i++) {
for (var j = i + 1; j < data.length; j++) {
var row = [];
data[0].forEach(function(e, k){
row.push(data[i][k]);
row.push(data[j][k]);
});
comparisonData.push(row);
}
}
// Writing the data to "Comparison" sheet
comparisonSheet.getRange(2, 1, comparisonData.length, comparisonData[0].length).setValues(comparisonData);
}
@deepakness
Copy link
Author

deepakness commented Jun 29, 2023

If your data in Google Sheets look like the below screenshot before running the script:

Before

Then it will look like the below screenshot after running the above script:

After

Just copy-paste the above script under Extensions > Apps Script and hit Run; you may asked for some permissions, allow them, and within seconds, all the combinations will be created.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment