I have to transpose the 4 unique dates into 4 columns in another sheet. The other sheet only has two columns and will need to add 2 more columns to accommodate the transpose using insertColumns
.
How can I achieve this using only Google Apps Script wherein the scripts checks whether the sheet has enough columns and inserts them accordingly if not?
function unique() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sheet1");
var lrow = sheet.getLastRow();
var range = sheet.getRange(2, 1, lrow-1, 1).getValues();
var unique = [...new Set(range)]
Logger.log(unique.length); // Not returning unique length - 7.0
}
CodePudding user response:
Unique Dates
function unique() {
var ss = SpreadsheetApp.getActive();
var sh = ss.getSheetByName("Sheet0");
var vs = sh.getRange(2, 1, sh.getLastRow() - 1).getValues().flat().map(d => d.valueOf());
var uvs = [...new Set(vs)].map(v => new Date(v));
if(sh.getMaxColumns() < uvs.length) {
sh.insertColumnsAfter(sh.getLastColumn(), uvs.length - sh.getLastColumn() - 1)
}
sh.clearContents();
sh.getRange(2,1,1,uvs.length).setValues([uvs]);
}
Before:
Date |
---|
1/1/2022 |
1/2/2022 |
1/3/2022 |
1/4/2022 |
1/4/2022 |
1/4/2022 |
1/4/2022 |
1/4/2022 |
1/4/2022 |
1/4/2022 |
After:
1/1/2022 | 1/2/2022 | 1/3/2022 | 1/4/2022 |