I am writing some Google Apps Script to get each Google Group and list it’s members then output it to a Google Sheet. Currently, I am grabbing each group and email address and pushing it to the memberArr, however I then want to ‘merge’ the relevant information.
So if for example, I have X Groups and Group 1 has 4 members (Foo, Bar, Baz and Quux) – Currently, it will output as
[ [ 'Group 1', 'Foo' ], [ 'Group 1', 'Bar' ], [ 'Group 1', 'Baz' ], [ 'Group 1', 'Quux' ] ]
But I want to have it output as [Group 1, Foo, Bar, Baz, Quux].
That is to say, merge the contents of the memberArr where there is a common Group
Here is my code so far:
function getAllGroupsTEST() {
const groupArr = [];
let gPageToken;
let gPage;
do {
gPage = AdminDirectory.Groups.list({
customer: "my_customer",
maxResults: 100,
gPageToken
});
const groups = gPage.groups;
if (groups) {
groups.forEach(({email}) => {
const groupEmail = email;
groupArr.push(groupEmail);
});
}
gPageToken = gPage.nextPageToken;
} while (gPageToken);
console.log(`LOGGING GROUPS:nn${groupArr}`);
const memberArr = [];
let mPageToken;
let mPage;
groupArr.forEach(group => {
mPage = AdminDirectory.Members.list(group,{
customer: "my_customer",
maxResults: 500,
mPageToken
})
const members = mPage.members;
if (members) {
// console.log(`LOGGING ${members.length} MEMBERS FOR ${group}nn${members}`)
members.forEach(member => {
// console.log(`MEMBER: ${member.email} IS IN GROUP ${group}`)
memberArr.push([group, member.email])
})
}
})
// console.log(`COUNTED ${groupArr.length} GROUPS`)
// console.log(memberArr)
}
Any help would be greatly appreciated!
Edit: Updated to show the memberArr as is rather than in a table format.
Advertisement
Answer
I’d propose to convert the array in the object and then back to the array this way:
var arr = [
['group1','a'],
['group1','b'],
['group2','c'],
['group2','d'],
['group3','e']
]
var obj = {}
for (var a of arr) {
try { obj[a[0]].push(a[1]) }
catch(e) { obj[a[0]] = [a[1]] }
}
console.log(obj);
var new_arr = [];
for (var group in obj) {
new_arr.push([group, ...obj[group]])
}
console.log(new_arr);Output:
[ [ 'group1', 'a', 'b' ], [ 'group2', 'c', 'd' ], [ 'group3', 'e' ] ]