If dynamic values exist somewhere else then format those values - google-apps-script

I am looking to find if non-consecutive dynamic values are found in another sheet B. If so, I want to format those values in Sheet A.
The problem with my code is that it is going through a range while the values I am looking for are not consecutive. So I'm not sure if a for loop is what should be used in this case.
function homeBoxlianTasks() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var todolistsheet = ss.getSheetByName("To-Do List")
var todolistliantaskvalues = todolistsheet.getRange("B6:B").getValues();
var todolistlianbackground = todolistsheet.getRange("B6:B").getBackgrounds()
var homeboxsheet = ss.getSheetByName("HomeBox");
var homeboxtaskvalues = homeboxsheet.getRange("homeboxtodotasks").getValues();
var backgrounds = [];
var fontLines = [];
//for each row that data is present
for(var i = 0; i < homeboxtaskvalues.length; i++) {
var ltValue = todolistliantaskvalues[i][0];
var hValue = homeboxtaskvalues[i][0];
var lbValue = todolistlianbackground[i][0];
if((hValue === ltValue) && lbValue === '#d9ead3') {
backgrounds.push(["#d9ead3"]);
fontLines.push(['line-through']);
}
else {
backgrounds.push([null]);
fontLines.push([null]);
}
}
homeboxsheet.getRange("homeboxtodotask1").setFontLines(fontLines).setBackgrounds(backgrounds);
}

Based on your reply:
I have 2 employees with a to-do list one under the other. Every time a task is done, there is a checkbox which will highlight and scratch the task in SheetA. I want that task to be also highlighted and scratched in Sheet B.
Try using an onEdit() trigger. Try the following code:
function onEdit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var summarySheet = ss.getSheetByName("Sheet1");
var range = e.range
var row = range.getRow()
var col = range.getColumn()
if (sheet.getName() == "Sheet0" && col == 1) {
var taskCell = sheet.getRange(row, col + 1)
var taskName = taskCell.getValue();
if (range.isChecked()) {
taskCell.setFontLine("line-through");
} else {
taskCell.setFontLine(null);
}
var checker = range.isChecked();
while (checker != null) {
row = row - 1
checker = sheet.getRange(row, col).isChecked();
}
var name = sheet.getRange(row - 1, col + 1).getValue();
var sumSheetRow = summarySheet.createTextFinder(name).findNext().getRow();
var sumSheetLastCol = summarySheet.getLastColumn();
var sumSheetCol = summarySheet.getRange(sumSheetRow,2,1,sumSheetLastCol-1).createTextFinder(taskName).findNext().getColumn();
var sumSheetTaskCell = summarySheet.getRange(sumSheetRow, sumSheetCol);
if (range.isChecked()) {
sumSheetTaskCell.setFontLine("line-through");
} else {
sumSheetTaskCell.setFontLine(null);
}
}
}
Result:
This also removes the strikethrough if unchecked:
Hope this helps!
EDIT:
Try:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh0 = ss.getSheetByName("Sheet0");
var sh1 = ss.getSheetByName("Sheet1");
function test() {
loopThroughTasks("Gaelle")
loopThroughTasks("Lian")
}
function loopThroughTasks(name) {
//ADD THE NAME AND RANGE IF NEEDED
if (name == "Gaelle") {
//Fixed Range and Start Row for Gaelle
var tasks = sh0.getRange("A6:B21").getValues();
var row = 6
} else if (name == "Lian") {
//Fixed Range and Start Row for Lian
var tasks = sh0.getRange("A24:B33").getValues();
var row = 24
}
for (var i = 0; i < tasks.length; i++) {
if (tasks[i][0] === 'Y') {
var sh1Cell = sh1.createTextFinder(tasks[i][1]).findNext().getCell(1, 1).getA1Notation()
sh0.getRange(row, 2).setBackground('#d9ead3')
.setFontLine('line-through');
sh1.getRange(sh1Cell).setBackground('#d9ead3')
.setFontLine('line-through');
} else if (tasks[i][0] === 'N' && tasks[i][1] != "") {
var sh1Cell = sh1.createTextFinder(tasks[i][1]).findNext().getCell(1, 1).getA1Notation()
sh0.getRange(row, 2).setBackground('#fff2cc')
.setFontLine(null);
sh1.getRange(sh1Cell).setBackground('#fff2cc')
.setFontLine(null);
};
row++
}
}

This is essentially your code:
function myfunk() {
var ss = SpreadsheetApp.getActive();
var sh1 = ss.getSheetByName("Sheet0")
var vs1 = sh1.getRange("B6:B" + sh1.getLastRow()).getValues();
var bg1 = sh1.getRange("B6:B" + sh1.getLastRow()).getBackgrounds()
var sh2 = ss.getSheetByName("Sheet1");
var vs2 = sh2.getRange("B6:B" + sh2.getLastRow()).getValues();
var backgrounds = [];
var fontLines = [];
for (var i = 0; i < vs2.length; i++) {
if ((vs2[i][0] === vs1[i][0]) && bg1[i][0] === '#ffffff') {
backgrounds.push(["#ffff00"]);
fontLines.push(['line-through']);
} else {
backgrounds.push([null]);
fontLines.push([null]);
}
}
sh2.getRange(6,2,fontLines.length,1).setFontLines(fontLines).setBackgrounds(backgrounds);
sh1.getRange(6,2,fontLines.length,1).setFontLines(fontLines).setBackgrounds(backgrounds);
}
Both sheet contain the same data
Sheet0:
COL1
COL2
COL3
COL4
COL5
COL6
COL7
COL8
COL9
COL10
7
10
9
3
10
5
7
1
10
7
0
2
4
0
9
9
9
7
7
3
1
6
2
6
4
9
1
8
8
3
2
1
8
5
1
1
4
4
1
10
0
6
10
8
5
10
1
10
10
7
9
7
0
9
5
8
6
3
10
5
8
7
9
7
8
3
0
1
5
9
6
1
4
9
5
6
4
0
6
7
2
2
8
7
5
6
8
10
7
7
6
0
1
9
4
9
7
2
7
0
0
4
8
1
2
4
4
0
2
2
Image of highlight output:
Non consecutive values can be found it's simply a line by line search. If it finds to elements in column B that are identical it highlight and strikes through.

Related

Sum two columns and display on third column

I want to sum two columns that have numerical values and display the results on the third column. I have the script below but that deletes the two columns and display the results on the first column.
Any suggestions?
function test2() {
var ss = SpreadsheetApp.getActiveSheet();
var rng = ss.getRange('E2:F6');
var val = rng.getValues();
for(row=0;row<val.length;row++) {
val[row][0] =val[row][0]+val[row][1];;
val[row][1] = '';
}
rng.setValues(val)
}
Try this instead. Just get the colum G and overwrite anything in it with the sum.
function test() {
var ss = SpreadsheetApp.getActiveSheet();
var rng = ss.getRange('E2:G6'); // just get the extra column
var val = rng.getValues();
for(row=0;row<val.length;row++) {
val[row][2] = val[row][0]+val[row][1];
val[row][1] = '';
}
rng.setValues(val)
}
Using map:
function one() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getActiveSheet();
const vs = sh.getRange('E2:F6').getValues().map(r => [r[0],r[1],r[0]+r[1]]);
sh.getRange(2,5,vs.length,vs[0].length).setValues(vs);
}
E
F
G
1
COL5
COL6
2
5
6
11
3
6
7
13
4
7
8
15
5
8
9
17
6
9
10
19
Array.map

Google Sheets script - For each used cell in range 1, if cell value exists in range 2, get range 2 match's row number

I feel I have this script almost working as intended, but I am unsure as to where to place certain components of the procedure within the for loop to achieve the desired result. Tunnel vision is very much in effect right now, it's entirely possible I am overthinking a simple task. Please let me know if I can describe the issue more clearly. Any suggestions or pointers towards an existing resource are helpful.
Setup: Sheet one contains a dynamic vertical list of text values starting in cell I3 going down. Sheet two contains a dynamic vertical list of text values starting in range A2 going down, and has a similar set of text values in the same rows in column B.
Goal:
Get the value of each used cell in Sheet1 column I (range one)
Get the value of each used cell in Sheet2 column A (range two)
For each used cell in range one, check the value of each range one
cell to see if the value exists in range two
If a match exists, get the row number of the cell in range two that
contains the value (there will only ever be a single match if a match
exists)
Get the value of the cell on that same row in Sheet2 column B
Set the above value as the cell value in the row containing the value
found in both ranges on Sheet1 Column M
Below is what I have been able to come up with. I am able to get it to function up to the last step. It seems the matching rowNumber variable is not updating with each for loop.
// Get values of range one
var lastRowRangeOne = sheetone.getRange('I3').getNextDataCell(SpreadsheetApp.Direction.DOWN).getRow();
var rangeOneValues = sheetone.getRange('I3:I' + lastRowClientColumn).getValues();
// Get values of range two
var sheettwo = spreadsheet.getSheetByName('Sheet2');
var sheettwoLastRow = sheettwo.getLastRow();
var sheettwoList = sheettwo.getRange('A2:A' + sheettwoLastRow).getValues();
var sheettwoListFlat = sheettwoList.map(function(row) {return row[0];});
for (var i = 0; i< rangeOneValues.length ; i++){ // for each row in range one
if (sheettwoListFlat[i] == rangeOneValues[i]) { // if the range one value exists in range two
var rowNumber = sheettwoListFlat.indexOf(rangeOneValues[i]) + 3; // get the row number of the matching value found in range two
var sheetOneColumnMValue = sheettwo.getRange('B' + rowNumber).getValue(); // get the cell value of the same row in sheet two column B
var sheetOneRowNumber = i + 3; // get the row number of the range one value
sheetone.getRange('M' + sheetOneRowNumber).setValue(sheetOneColumnMValue); // set the cell value of sheet one column M row x, where x is sheetOneRowNumber
}
}
If you print the value of sheettwoListFlat, it has only 5 elements. Once the iterator of for loop reaches 5 or more it will automatically set if (sheettwoListFlat[i] == rangeOneValues[i]) { to false. Also the statement will only work if the elements of the same index of both arrays are equal.
It would be also more efficient if you search the Sheet1 using the values of Sheet2 since Sheet2 has lesser value.
Here I used TextFinder to find the text within a range.
Using Sheet2 values as search key
Code:
function myFunction() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheetone = spreadsheet.getSheetByName('Sheet1');
var lastRowRangeOne = sheetone.getRange('I2').getNextDataCell(SpreadsheetApp.Direction.DOWN).getRow();
var rangeOneValues = sheetone.getRange('I2:I' + lastRowRangeOne);
var sheettwo = spreadsheet.getSheetByName('Sheet2');
var sheettwoLastRow = sheettwo.getLastRow();
var sheettwoList = sheettwo.getRange('A2:B' + sheettwoLastRow).getValues();
for (var i = 0; i < sheettwoList.length; i++){
var find = rangeOneValues.createTextFinder(sheettwoList[i][0]).findNext()
if(find){
var sheetOneRowNumber = find.getRow();
sheetone.getRange('M' + sheetOneRowNumber).setValue(sheettwoList[i][1]);
}
}
}
Using Sheet1 values as search key
Code:
function myFunction() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheetone = spreadsheet.getSheetByName('Sheet1');
var lastRowRangeOne = sheetone.getRange('I2').getNextDataCell(SpreadsheetApp.Direction.DOWN).getRow();
var rangeOneValues = sheetone.getRange('I2:I' + lastRowRangeOne).getValues();
var sheettwo = spreadsheet.getSheetByName('Sheet2');
var sheettwoLastRow = sheettwo.getLastRow();
var sheettwoList = sheettwo.getRange('A2:B' + sheettwoLastRow);
for (var i = 0; i< rangeOneValues.length ; i++){ // for each row in range one
var find = sheettwoList.createTextFinder(rangeOneValues[i][0]).findNext();
if(find){
var rowNumber = find.getRow()
var sheetOneColumnMValue = sheettwo.getRange('B' + rowNumber).getValue(); // get the cell value of the same row in sheet two column B
var sheetOneRowNumber = i + 2;
sheetone.getRange('M' + sheetOneRowNumber).setValue(sheetOneColumnMValue);
}
}
}
Output:
Note: Both produce the same output but using Sheet2 values as search key is more faster than the other.
function compareTwoCols() {
const c1 = 'COL1';//column names
const c2 = 'COL3';
const ss1 = SpreadsheetApp.openById(gobj.globals.datagenid);//data set 1
const sh1 = ss1.getSheetByName('Sheet1');
const [hd1, ...vs1] = sh1.getDataRange().getValues();
let col1 = {};
hd1.forEach((h, i) => { col1[h] = i });
const ds1 = vs1.map((r, i) => {
return r[col1[c1]];
});
const ss2 = SpreadsheetApp.openById(gobj.globals.ssid);//data set 2
const sh2 = ss2.getSheetByName('Sheet0');
const [hd2, ...vs2] = sh2.getDataRange().getValues();
let col2 = {};
hd2.forEach((h, i) => { col2[h] = i });
const ds2 = vs2.map((r, i) => {
return r[col2[c2]]
});
let matches = { pA: [] };
let idx = -1;
ds1.forEach((e, i) => {
let from = '';
do {
idx = ds2.indexOf(e, from);
if (~idx) {
if (!matches.hasOwnProperty(e)) {
matches[e] = [];
matches[e].push({ val1: e, row1: i + 2, col1: col1[c1] + 1, row2: idx + 2, col2: col2[c2] +1 });
matches.pA.push(e);
} else {
matches[e].push({ val1: e, row1: i + 2, col1: col1[c1] + 1, row2: idx + 2, col2: col2[c2] + 1});
}
from = idx + 1;
}
} while (~idx);
});
Logger.log(JSON.stringify(matches));
}
Spreadsheet1 Sheet1:
COL1
COL2
COL3
COL4
COL5
3
4
2
3
4
2
6
6
1
4
5
1
7
5
5
9
8
7
9
5
7
9
0
8
1
8
2
8
7
9
5
8
7
9
9
1
2
0
8
6
2
7
4
0
3
8
2
0
2
6
Spreadsheet2 Sheet0:
COL1
COL2
COL3
COL4
COL5
5
1
2
7
6
4
5
7
8
2
6
3
8
1
5
0
7
6
3
6
4
7
6
1
7
5
6
9
2
1
3
0
2
2
8
4
5
0
8
1
1
3
9
2
2
3
6
7
0
3
Matches Object:
{
"2":[
{
"val1":2,
"row1":3,//ds1 row 3
"col1":1,
"row2":2,//ds2 row 4
"col2":3
},
{
"val1":2,
"row1":3,//ds1 row 3
"col1":1,
"row2":8,//ds2 row 8
"col2":3
},
{
"val1":2,
"row1":10,
"col1":1,
"row2":2,
"col2":3
},
{
"val1":2,
"row1":10,
"col1":1,
"row2":8,
"col2":3
}
],
"7":[
{
"val1":7,
"row1":6,
"col1":1,
"row2":3,
"col2":3
},
{
"val1":7,
"row1":6,
"col1":1,
"row2":11,
"col2":3
}
],
"8":[
{
"val1":8,
"row1":7,
"col1":1,
"row2":4,
"col2":3
},
{
"val1":8,
"row1":11,
"col1":1,
"row2":4,
"col2":3
}
],
"9":[
{
"val1":9,
"row1":5,
"col1":1,
"row2":7,
"col2":3
},
{
"val1":9,
"row1":5,
"col1":1,
"row2":10,
"col2":3
}
],
"pA":[//just an array of all of the matches
2,
9,
7,
8
]
}

Google Script - Internal Error after 15 seconds

So I am writing a script that we give the sum of all the data that has a specific tag in the same row.
Col 1 | Col 2
-------+---------
grp1 | 2
grp1 | 1
grp2 | 1
-------+---------
If I was to pass this function grp1 the result would be 3.
When I use this script over 1000 rows, I get an error "Internal Error Executing the custom function" after a short time (like 15 seconds). I thought it might be the timeout but it happens well before 30 seconds. Any ideas?
function collectgrpdata(group, startrow) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var lastrow = sheet.getLastRow();
var currentcell = sheet.getActiveCell();
var col = currentcell.getColumn();
var total = 0;
for(var x = startrow; x <= lastrow; x++) {
var v = sheet.getRange(x, col).getValue();
if(v != "" ) {
if (sheet.getRange(x, 2).getValue() == group) {
total += v;
}
}
}
return total
}
Your problem is most likely due to the fact that you do so many calls to getRange and getValue.
You are probably hitting your quota limit of calls.
instead of doing that do one big call to get all the data and then work with that:
function collectgrpdata2(group, startrow) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var currentcell = sheet.getActiveCell();
var col = currentcell.getColumn();
var range = sheet
.getRange(startrow,
col,
sheet.getLastRow() - startrow + 1,
sheet.getLastColumn() - col + 1)
var data = range.getValues();
return data
.filter(function(row) {return row[0] === group;})
.map(function(row) {return row[1];})
.concat(0)
.reduce(function(x,y) {return x+y;});
}

Google Script: Delete row if a value in it exists in more than one sheet

I had posted a question months ago regarding deleting a row if a value in it exists in another sheet.
This is the accepted answer in my previous post.
function deleteRowInSheet1() {
var s1 = SpreadsheetApp.openById("SS_ID").getSheetByName('Sheet1');
var s2 = SpreadsheetApp.openById("SS_ID").getSheetByName('Sheet2');
var values1 = s1.getDataRange().getValues();
var values2 = s2.getDataRange().getValues();
var resultArray = [];
for(var n in values1){
var keep = true
for(var p in values2){
if( values1[n][0] == values2[p][0] && values1[n][1] == values2[p][1]){
keep=false ; break ;
}
}
if(keep){ resultArray.push(values1[n])};
}
s1.clear()
s1.getRange(1,1,resultArray.length,resultArray[0].length).setValues(resultArray);
}
Now, my question is what if there are more than 1 sheet to be compared to. Let's say I have 4 sheets.
Sheet1:
NAME | PLACE | AGE
Carl | Florida | 45
Mike | Florida | 41
Suzy | Florida
Sheet 2:
NAME | PLACE | AGE
Mike | Florida | 41
Sheet 3:
NAME | PLACE | AGE
Mike | Florida | 41
Sheet 4:
NAME | PLACE | AGE
Mike | Florida | 41
The script should delete Mike Florida row in Sheet 2 to 4 since it has duplicate data in Sheet 1. Column 1 and 2, again are the basis to compare all the data in the 4 sheets since the values will be unique. I tried to modify the answered script but I can't seem to make it run. I understood the logic but not sure which part I missed:
This is my code:
function deleteRowInSheets1to3() {
var s1 = SpreadsheetApp.openById("SS_ID").getSheetByName('Sheet1'); //this is the basis of all sheets. values to be compared is column 2
var s2 = SpreadsheetApp.openById("SS_ID").getSheetByName('Sheet2');
var s3 = SpreadsheetApp.openById("SS_ID").getSheetByName('Sheet3');
var s4 = SpreadsheetApp.openById("SS_ID").getSheetByName('Sheet4');
var values1 = s1.getDataRange().getValues();
var values2 = s2.getDataRange().getValues();
var values3 = s3.getDataRange().getValues();
var values4 = s4.getDataRange().getValues();
var resultArray = [];
for(var n in values1){
var keep = true
for(var p in values2){
if( values1[n][0] == values2[p][0] && values1[n][1] == values2[p][1]){
keep=false ; break ;
}
for(var q in values3){
if( values1[n][0] == values3[q][0] && values1[n][1] == values3[q][1]){
keep=false ; break ;
}
for(var r in values4){
if( values1[n][0] == values4[r][0] && values1[n][1] == values4[r][1]){
keep=false ; break ;
}
}
}
}
if(keep){ resultArray.push(values1[n])};
}
s1.clear()
s1.getRange(1,1,resultArray.length,resultArray[0].length).setValues(resultArray);
}
Thanks a bunch for any advice! :)
I think we almost have the same situation. This is a possible duplicate question. See this post.
The answer provided was below (not my code):
function removeDupsInOtherSheets() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s1 = ss.getSheetByName("Sheet1").getDataRange().getValues();
var s2 = ss.getSheetByName("Sheet2").getDataRange().getValues();
var s3 = ss.getSheetByName("Sheet3").getDataRange().getValues();
// iterate s3 and check in s1 & s2 if duplicate values exist
var nS1 = [];
var nS2 = [];
var s3Col1 = [];// data in column1 of sheet3
for(var n in s3){
s3Col1.push(s3[n][0]);
}
for(var n in s1){ // iterate sheet1 and test col 1 vs col 1 in sheet3
var noDup1 = checkForDup(s1[n],s3Col1)
if(noDup1){nS1.push(noDup1)};// if not present in sheet3 then keep
}
for(var n in s2){ // iterate sheet2 and test col 1 vs col 1 in sheet3
var noDup2 = checkForDup(s2[n],s3Col1)
if(noDup2){nS2.push(noDup2)};// if not present in sheet3 then keep
}
Logger.log(nS1);// view result
Logger.log(nS2);
ss.getSheetByName("Sheet1").getDataRange().clear();// clear and update sheets
ss.getSheetByName("Sheet2").getDataRange().clear();
ss.getSheetByName("Sheet1").getRange(1,1,nS1.length,nS1[0].length).setValues(nS1);
ss.getSheetByName("Sheet2").getRange(1,1,nS2.length,nS2[0].length).setValues(nS2);
}
function checkForDup(item,s){
Logger.log(s+' = '+item[0]+' ?')
if(s.indexOf(item[0])>-1){
return null;
}
return item;
}
Hope this helps.

merge values in column in a row with the quotes separator "|", based on a comparison with the values of another column

as the title suggests I'm trying to find a way to treat some data in a spreadsheet to google app.
I think the best way is to directly set an example and thank you in advance for your support as always.
simply:
sheet1 (colA, colB)
sheet2 (colA', colB')
sheet1
colA colB
1 xxx 40
2 xxx 42
3 yyy 42
4 yyy 44
. ... etc.
sheet2
colA' colB'
1 xxx 40 | 42
2 yyy 42 | 44
3 ... .. | .. (etc.)
I would be grateful for a hint of code to google app script.
thanks
Gì
EDIT (in progress)
hi,
I hope that by sharing the file answer your questions.
the sheet already exist, the code is written in part and I would need help on this.
there is no duplication in ColumnB for article xxx or yyy or zzz etc. ..
in sheet "sheet_demo" indicates that the script should be.
Spreadsheeet demo
function merge_col() {
var sheet = SpreadsheetApp.openById("0AiuqXkUqDMgzdFM5aVNxeEhPbWFmbGhybl9TVkt4ZWc");
var ss_sorg = sheet.getSheetByName('sheet1');
var ss_dest = sheet.getSheetByName('sheet2');
var sorg_data = ss_sorg.getRange("A2:C").getValues();
var dest_data = ss_dest.getRange("A2:C").getValues();
var dest_Cod = [];
var dest_Des = [];
var temp_Cod, temp_Des;
for (var i = 0; i < sorg_data.length; i++) {
temp_Cod = null;
temp_Des = null;
for (var j = 1; j < sorg_data.length; j++) {
if (sorg_data[i][0] == sorg_data[j][0].toString().match(sorg_data[i][0]) && sorg_data[i][0] != "") {
temp_Cod = sorg_data[i][1];
temp_Des = sorg_data[i][2];
break;
}
}
dest_Cod.push([temp_Cod]);
dest_Cod.join('|');
dest_Des.push([temp_Des]);
dest_Des.join('|');
}
if (dest_Cod.length > 0 || dest_Des.lenght > 0) {
ss_dest.getRange(2, 2, dest_Cod.length, 1).setValues(dest_Cod); Logger.log(dest_Cod)
ss_dest.getRange(2, 3, dest_Des.length, 1).setValues(dest_Des); Logger.log(dest_Des)
}
}
EDIT (FINAL)
TKS Serge!
function merge_col() {
var ss = SpreadsheetApp.getActive().getSheetByName('sheet1');
var data = ss.getDataRange().getValues();
var header = data.shift();
var col1 = data[1][0];
var col2 = '';
var col3 = '';
var dataSheet2 = [header];
for(var i=0 ; i<data.length ; i++){
Logger.log(data[i][0]+' - '+col1+' - '+data[i][2])
if(col1==data[i][0]){
col1 = data[i][0];
col2+=data[i][1]+' | ';
col3+=data[i][2]+' | ';
}else{
dataSheet2.push([col1,col2,col3]);
var col1 = data[i][0];
col2 = data[i][1]+' | ';
col3 = data[i][2]+' | ';
}
}
dataSheet2.push([col1,col2,col3]);
Logger.log(dataSheet2);
var sheet2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('sheet2');
sheet2.clear();
sheet2.getRange(1, 1, dataSheet2.length, dataSheet2[0].length).setValues(dataSheet2);
}
Here is a code that does exactly what you expected using a simple loop and a comparison.
function merge_col() {
var ss = SpreadsheetApp.getActive().getSheetByName('sheet1');
var data = ss.getDataRange().getValues();
var header = data.shift();
var col1 = data[1][0];
var col2 = '';
var col3 = '';
var dataSheet2 = [header];
for(var i=0 ; i<data.length ; i++){
Logger.log(data[i][0]+' - '+col1+' - '+data[i][2])
if(col1==data[i][0]){
col1 = data[i][0];
col2+=data[i][1]+' | ';
col3+=data[i][2]+' | ';
}else{
dataSheet2.push([col1,col2,col3]);
var col1 = data[i][0];
col2 = data[i][1]+' | ';
col3 = data[i][2]+' | ';
}
}
dataSheet2.push([col1,col2,col3]);
Logger.log(dataSheet2);
var sheet2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('sheet2');
sheet2.clear();
sheet2.getRange(1, 1, dataSheet2.length, dataSheet2[0].length).setValues(dataSheet2);
}
have a look at this post, he want to do almost the same. Modifying 2 lines of the code and it's done:
function myFunction() {
var objList={};
var ss = SpreadsheetApp.getActive().getActiveSheet();
var data = ss.getDataRange().getValues();
for(var i in data){
// for(var j in data[i]){
if(typeof objList[data[i][0]]=="undefined"){
objList[data[i][0]]=[]; // new array
objList[data[i][0]].push(data[i][1]); // push the value of the second column
}
else{
objList[data[i][0]].push(data[i][1]);
}
//}
}
var objTable=[];
for(var k in objList){
objTable.push([k,objList[k]]);
}
Logger.log(objTable);
ss.clear();
ss.getRange(1, 1, objTable.length, objTable[0].length).setValues(objTable);
}