1

I am trying to get a list of people in a Google Group with Google Apps Script. I made a code (below) but the result is unexpected. I think is realted with the format of the item but not sure. In my code i tested many logs to check that.

Why "indexOf" can not detect properly the email? Becuase -1.00 as answer is wrong.

Info: getUsers() User[] Retrieves the direct members of the group that have a known corresponding Google account.

I think is weird indexOf answering -1.00 when i ask with "" and when i ask with the position of array answer properly.

I need to check in an script if someone is inside of this groups (inside loop for).

function CheckingSomeFromGroup() {
  var members = GroupsApp.getGroupByEmail("members@company").getUsers();

  Logger.log(members); //it shows an array in the log
  Logger.log(members[0]); //it shows the first element form that array which is "Jorge@company.com"
  Logger.log(members.indexOf("Jorge@company.com") //i was expecting a number different than -1.00 because jorge exists but in the log appear -1.00 which is wrong
  Logger.log(members.indexOf(members[0]); //it shows 0 correctly becuase Jorge is in the first place of the array
  Logger.log(members.length);//it shows number 3 which is ok since i have 3 people in the group

}
Juanchr
  • 11
  • 2

1 Answers1

1

members is an array of User object, not string. So you cannot just find it by email/string. You see email in the logger because it might have a toString method to output that.

You can loop on members and call User.getEmail() to get the email and work accordingly.

function CheckingSomeFromGroup() {

    var emails = ['abc@example.com'];//get 1-D array of string emails from your column accordingly

    var members = GroupsApp.getGroupByEmail("members@company").getUsers();

    for (var i = 0; i < members.length; i++) {
        var memberEmail = members[i].getEmail();

        if (emails.indexOf(memberEmail) !== -1) {
//exists
        }

    }

}
Karan
  • 1,187
  • 2
  • 9
  • 16
  • Oh nice. But why indexOf(members[0]) works perfectly? I have a column in Google Sheet with a lot of emails and i need to check if each email is in that group (with a loop for). How can i use indexOf in this case? – Juanchr Dec 09 '21 at 08:48
  • 1
    because members[0] is a user object still, not string. I have edited the answer for how you can get the user's email. if you log `members[0].getEmail()` you will get the email string value. so you can do `members[i].getEmail()` in a loop. – Karan Dec 09 '21 at 08:51
  • Then i must make 2 loops? 1 Loop to check every e-mail in my array and another loop to go 1by1 in this Objet with email groups? Is there any way to convert that members object in an array? then i can forget the 2th loop and use indexof. – Juanchr Dec 09 '21 at 08:55
  • Not necessarily. If you can get the list of emails to compare against then you can do something like the updated answer code – Karan Dec 09 '21 at 08:59