Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

102
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!