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

101
Visualizações
Javascript - Count first element of multi dimensional array

I have below code to extract the ID and username of a unique list of authors.

    let authorsList = await Poem.find({ 'author.id': {$nin: community.busAdmins}}).where('communities').equals(community._id).populate('authors').sort({"author.username": 1});

    let uniqueAuthorsList = [];
    authorsList.forEach(details => {
        if(!uniqueAuthorsList.some(code => code.username == details.author.username)){
            uniqueAuthorsList.push({username: details.author.username, id: details.author.id});
        }
    });

For each of those authors, I want to count how many blogs they have written. So far I have this code:

const counts = {};
        uniqueAuthorsList.forEach((el) => {
        counts[el] = counts[el] ? (counts[el] += 1) : 1;
        });
        console.log(counts);

But this only returns:

{ '[object Object]': 7 }

How can I count the records using only the first element of the array (username), so I can return a list like this?

Dave: 4
Emily: 7
Mark: 2
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Put the counts in uniqueAuthorsList when you're creating it.

let uniqueAuthorsList = [];
authorsList.forEach(details => {
  let author = uniqueAuthorsList.find(code => code.username == details.author.username);
  if (author) {
    author.count++;
  } else {
    uniqueAuthorsList.push({
      username: details.author.username,
      id: details.author.id,
      count: 1
    });
  }
});

You might want to just make uniqueAuthors an object rather than an array.

let uniqueAuthors = {};
authorsList.forEach(details => {
  if (uniqueAuthors[details.author.username]) {
    uniqueAuthors[details.author.username].count++;
  } else {
    uniqueAuthors[details.author.username] = {
      username: details.author.username,
      id: details.author.id,
      count: 1
    };
  }
});
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