Попробуйте этот код.Сначала удалите conversion notes
строки с листа RAW
.
function test() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var rawSheet = ss.getSheetByName('RAW');
var rawValues = rawSheet.getDataRange().getValues();
rawValues.shift();
// will be months present in data
// { 0: true, 1: true ... }
var mos = {};
// well be vendors present in data
// { Google: true ... }
var vens = {};
// data structure
var ds = {};
rawValues.forEach(function(row) {
// check below cols
var month = Math.floor(new Date(row[2]).getMonth());
var zone = row[12];
var ven = row[13];
mos[month] = true; // set month on mos
vens[ven] = true; // set vendor on vens
ds[zone] = ds[zone] || {}; // zone
ds[zone][ven] = ds[zone][ven] || {}; // vendor
// set conversion value
if (!ds[zone][ven][month]) {
ds[zone][ven][month] = [
// A
parseInt(row[4]) + parseInt(row[5]),
// B
parseInt(row[6]) + parseInt(row[7]),
// C
parseInt(row[8]) + parseInt(row[9]),
// D
parseInt(row[10]) + parseInt(row[11])
];
} else {
ds[zone][ven][month] = [
// A
ds[zone][ven][month][0] + parseInt(row[4]) + parseInt(row[5]),
// B
ds[zone][ven][month][1] + parseInt(row[6]) + parseInt(row[7]),
// C
ds[zone][ven][month][2] + parseInt(row[8]) + parseInt(row[9]),
// D
ds[zone][ven][month][3] + parseInt(row[10]) + parseInt(row[11])
];
}
});
Logger.log(vens);
// put empty vendor for a zone if not exists
Object.keys(ds).forEach(function(z) {
ds[z] = ds[z] || {};
Object.keys(vens).forEach(function(v) {
ds[z][v] = ds[z][v] || {};
});
});
// Logger.log(ds);
var months = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11'];
// filter months to get months present in sheet data in order
months = months.filter(function(m) {
return mos[m] == true;
});
// Logger.log(months);
// Z : { V: [ row, row... ]... }
var rs = {};
Object.keys(ds).forEach(function(z) {
rs[z] = rs[z] || {};
Object.keys(ds[z]).forEach(function(v) {
rs[z][v] = rs[z][v] || [];
months.forEach(function(m) {
if (ds[z][v][m]) {
rs[z][v].push(ds[z][v][m]);
} else {
rs[z][v].push(['N/A', 'N/A', 'N/A', 'N/A']);
}
});
});
});
// Logger.log(rs);
// start of vendors in all sheets, [row, col]
// must be same in all zone sheets, which is now
var pos = {
Google: [3, 7],
Nielsen: [21, 7],
IBM: [39, 7],
Samsung: [57, 7]
};
// write rows
Object.keys(rs).forEach(function(z) {
try {
ss.insertSheet(z);
} catch (e) {}
var sh = ss.getSheetByName(z);
Object.keys(rs[z]).forEach(function(v) {
sh.getRange(pos[v][0], pos[v][1], rs[z][v].length, 4).setValues(rs[z][v]);
});
});
}