Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

130
Visualizações
Merging contents of an array based on matching content

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:\n\n${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}\n\n${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.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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' ] ]
about 4 years ago · Juan Pablo Isaza Relatório

0

I like @YuriKhristich solution. However, I still want to post this code showing how you could make a few minor changes to your existing code to build your required data structure.

We start by initializing a list with the group email. Next we append all the member emails to the list. And finally we push the completed list to memberArr. The advantage is that this builds the required data format while the data is read rather than trying to rework it afterward.

    let list = [group];  // <-- ADD

    if (members) {
        members.forEach(member => {
          
          // memberArr.push([group, member.email])  <-- REMOVE
          
          list.push(member.email);   // <-- ADD
          
        })
        memberArr.push(list);  // <-- ADD
     }
  })

// Simulated Google Groups data

var gPage = {
  groups: [
    {id: 1, name: "Group 1", email: "group1@emal.com" },
    {id: 2, name: "Group 2", email: "group2@emal.com" },
    {id: 3, name: "Group 3", email: "group3@emal.com" }
  ]
};

var mPage = { 
  members: [
    {id: 1, role: "admin", email: "member1@email.com" },
    {id: 2, role: "admin", email: "member2@email.com" },
    {id: 3, role: "admin", email: "member3@email.com" },
    {id: 4, role: "admin", email: "member4@email.com" },
    {id: 5, role: "admin", email: "member5@email.com" }
  ]
};


function getAllGroupsTEST() {

  const groupArr = [];
  let gPageToken;
  //let gPage;

  do {
    
    /* useing fake data
    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);



  const memberArr = [];
  let mPageToken;
  //let mPage;

  groupArr.forEach(group => {
  
     /* using fake data
      mPage = AdminDirectory.Members.list(group,{
        customer: "my_customer",
        maxResults: 500,
        mPageToken
      })
    */


    const members = mPage.members;

    let list = [group];

    if (members) {
        members.forEach(member => {
          
          // memberArr.push([group, member.email])
          
          list.push(member.email);
          
        })
        
        memberArr.push(list);
        
     }
    
  })

  return memberArr;

}

console.log( getAllGroupsTEST() );

about 4 years ago · Juan Pablo Isaza Relatório

0

You can implement this easy function for every group you want to filter

Take into account that this will eliminate every duplicate of the array.

const dataToFiler = [['Group 1', 'Foo'],
['Group 1', 'Bar'],
['Group 1', 'Baz'],
['Group 1', 'Quux']]

const filterRD = (arr) => {
  return [...new Set(arr.flat())]
}

console.log(filterRD(dataToFiler))

Documentation
  • Set
  • Array.prototype.flat()
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda