The script below copies rows from multiple sheets and append them to a master spreadsheet. But it ends up producing way too many duplicates. I mean it copies and appends the content from the other sheets without the possibility of checking, if these rows and their respective content already exist in the master spreadsheet.
Here is the script:
function copyAndAddNewEntries() {
// Get ID of each source spreadsheet and name of each source sheet
var spreadsheets = [
{ssId: 'SOURCE_SHEET_ID1', sheetNames: ["Sheet1", "Sheet2",,,]},
{ssId: 'SOURCE_SHEET_ID2', sheetNames: ["Sheet1", "Sheet2",,,]},
,,
,
];
// Copy the relevant rows/content from each of the spreadsheets and sheets listed above
var {values, max} = spreadsheets.reduce((o, {ssId, sheetNames}) => {
SpreadsheetApp.openById(ssId).getSheets().forEach(s => {
if (sheetNames.includes(s.getSheetName())) {
var [, ...v] = s.getDataRange().getValues();
var temp = v.filter(e => e.join("") != "");
if (temp.length > 0) {
o.values = o.values.concat(temp);
var len = temp.length;
o.max = o.max < len ? len : o.max;
}
}
});
return o;
}, {values: [], max: 0});
values = values.map(r => {
var len = r.length;
return len < max ? r.concat(Array(max - len)) : r;
});
// Add the rows/content that were copied above to the MASTER WORKSHEET
var targetSheet = SpreadsheetApp.openById('TARGET_SHEET_ID').getSheetByName('TARGET_SHEET_NAME');
targetSheet.getRange(targetSheet.getLastRow() + 1, 1, values.length, values[0].length).setValues(values);
}
I am wondering how I can add in the script below from Google Apps Script official website (and which I have slightly modified) to check my data before the new rows are appended to the master spreadsheet. All script examples I´ve seen so far do the job afterwards (so, only after the new rows have been added). But I need the check to happen before or during the process of adding these rows.
function removeDuplicates() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("NAME_OF_MASTER_SPREADSHEET");
var data = sheet.getDataRange().getValues();
// var sheet = SpreadsheetApp.getActiveSheet();
var newData = [];
for (var i in data) {
var row = data[i];
var duplicate = false;
for (var j in newData) {
if (row.join() == newData[j].join()) {
duplicate = true;
}
}
if (!duplicate) {
newData.push(row);
}
}
sheet.clearContents();
sheet.getRange(1, 1, newData.length, newData[0].length).setValues(newData);
}
Thank you so much in advance for your help :)