-
Notifications
You must be signed in to change notification settings - Fork 0
/
Grouper.js
42 lines (34 loc) · 1.16 KB
/
Grouper.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
function groupRawDataByMonth() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sourceSheet = ss.getSheetByName("Raw");
const sourceData = sourceSheet.getDataRange().getValues();
if (sourceData.length < 2) {
return [];
}
const header = sourceData[0];
const rows = sourceData.slice(1);
const monthGroups = {};
rows.forEach(row => {
const recordTimestamp = row[0];
if (!(recordTimestamp instanceof Date)) {
return;
}
const yearMonth = `${recordTimestamp.getFullYear()}-${recordTimestamp.toLocaleString("en-US", { month: "long" })}`;
if (!monthGroups[yearMonth]) {
monthGroups[yearMonth] = [];
}
monthGroups[yearMonth].push(row);
});
Object.keys(monthGroups).forEach(yearMonth => {
let sheet = ss.getSheetByName(`Raw-${yearMonth}`);
if (!sheet) {
sheet = ss.insertSheet(`Raw-${yearMonth}`);
} else {
sheet.clear();
}
const dataToWrite = [header, ...monthGroups[yearMonth]];
sheet.getRange(1, 1, dataToWrite.length, header.length).setValues(dataToWrite);
});
SpreadsheetApp.flush();
return Object.keys(monthGroups).map(yearMonth => `Raw-${yearMonth}`);
}