thank you ahead for your time and efforts.
Could you help me fix this script so that I can copy range from 'source' tab to 'target'tab as opposed to just a column? Currently it is copying only the column and column header. The 'source' tab will have data constantly refreshed from sql add-in and wish to only add new unique data to the bottom of 'target' tab (based on id in column A) while ignoring duplicate IDs in column A.
function keepUnique(){
var col = 0 ; // choose the column you want to use as data source (0 indexed, it works at array level)
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ms = ss.getSheetByName("source");
var sh = ss.getSheetByName("target");
var ss = SpreadsheetApp.getActiveSpreadsheet();
var data=ms.getDataRange().getValues();// get all data
Logger.log(data);
var newdata = new Array();
for(nn in data){
var duplicate = false;
for(j in newdata){
if(data[nn][col] == newdata[j][0]){
duplicate = true;
}
}
if(!duplicate){
newdata.push([data[nn][col]]);
}
}
Logger.log(newdata);
sh.getRange(3,1,newdata.length,newdata[0].length).setValues(newdata);// paste new values sorted in column of your choice (here column 8, indexed from 1, we are on a sheet))
}
CodePudding user response:
Use reduce
to filter out unique values and splice
to only return starting from the 2nd row of the data (excluding the header).
function keepUnique(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ms = ss.getSheetByName("source");
var sh = ss.getSheetByName("target");
var ss = SpreadsheetApp.getActiveSpreadsheet();
var data = ms.getDataRange().getValues();
var newdata = data.reduce((a, c) => {
// if column a is unique, include in the data
if (!a.find(v => v[0] === c[0])) {
a.push(c);
}
return a;
// remove header
}, []).splice(1);
// write data starting from A3
sh.getRange(3, 1, newdata.length, newdata[0].length).setValues(newdata);
}