I have the following code which creates Google Contacts from a Spreadsheet. The problem is whenever I run the code it creates contacts but has no functionality to check if the same Google Contact already exists or not.
This piece of code retrieves the contacts of the group first and checks whether an e-mail address corresponds to one of the sheet entries:
Code
function bulk_cdb_one_way_sync(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var cdb = ss.getSheetByName("Bulk_CDB").getDataRange().getValues();
var group = ContactsApp.getContactGroup("Preview List");
var groupContacts = ContactsApp.getContactGroup("Preview List").getContacts();
for (var x=1, xLen=cdb.length; x<xLen; x++) {
var aContact = [];
aContact.push(cdb[x][0], cdb[x][1], cdb[x][2], cdb[x][6]);
var c = 0;
if(groupContacts.length > 0) {
c =+ 1, u = 0;
for(var i in groupContacts) {
var emails = groupContacts[i].getEmails();
for(var j in emails) {
if(emails[j].getAddress() == aContact[2]) {
u += 1;
continue;
}
}
}
}
if(c === 0 || u == "undefined" || u === 0) {
var c = ContactsApp.createContact("There","Painter", aContact[2]);
c.addCustomField("Metro 1", aContact[1]);
c.addCustomField("Status", aContact[0]);
c.addPhone(ContactsApp.Field.WORK_PHONE, aContact[3]);
c.addToGroup(group);
}
}
}
Explained
The groupContacts
retrieves all available contacts in the group. The x=1
makes sure to skip the header and the array (aContact
) is created for easy access. If the group has no entries, then c
will remain 0
and the new contacts will be added. Then the script will itterate over the contacts and over the e-mails present. If a match is found, u
will be > 0
and no contact is added.
Remark
Make sure the data you about to add contains no duplicates.....
-
I tried with your code, still duplicate entries can be added to group. I there is no contact added to group then its not adding contact ? any suggestions – Noor Aug 24 '13 at 15:26
-
@Noor this was one of my first
I did not test in advance
scripts. I hope this one works. – Jacob Jan Tuinstra Aug 24 '13 at 19:07