Last active
June 29, 2023 05:32
-
-
Save deepakness/0e437ff56f703121b0c636c3ee1580d9 to your computer and use it in GitHub Desktop.
Create comparisons of "Product 1" vs "Product 2" right inside Google Sheets.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If your data in Google Sheets look like the below screenshot before running the script:
Then it will look like the below screenshot after running the above script:
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.